#!/usr/bin/python
#-*- coding=utf-8 -*-

from __future__ import absolute_import, print_function, division
import tflearn
import tensorflow as tf
#import network as network
#import network_tune as network
import network_log_inp_ma as network
import json

import os
import random
import numpy as np
import sys

from okex_websocket import Websocket
import logging
from time import sleep
import time
import pdb
import traceback
import pandas as pd
import datetime
import requests
import math
import pickle
import copy
import gzip
import zlib

import okex.spot_api as spot
import binascii
import okex.consts as c 
import dateutil.parser as dp

import threading
import ctypes
import random

class agent:
    def __init__(self,cfg_path,model):
        tf.reset_default_graph()
        fid = open(cfg_path, 'r')
        config = json.load(fid)
        #restore_dir=None
        self.__config = config
        self.__coin_number = config["input"]["coin_number"]
        self.__net = network.CNN(config["input"]["feature_number"],
                                 self.__coin_number,
                                 config["input"]["window_size"],
                                 config["layers"])
        self.sess = tf.Session()
        self.sess.run(tf.global_variables_initializer())
        saver = tf.train.Saver()
        saver.restore(self.sess, model)
    
    @property
    def net(self):
        return self.__net
    
    def predict(self,xt):
        w_t = self.sess.run(self.net.output, feed_dict={self.net.input_num: 1,  self.net.input_tensor: xt})
        return w_t

class getOkexData(Websocket) :
    def __init__(self, endPoint, symbol, apiKey, apiSecret, passphrase):
        #####时间相关#####
        #上一交易时间(获取交易数据模块使用)
        self._trade_pre_time = ''
        #上一交易时间(下单模块使用)
        self._order_pre_time = ''
        #最新交易时间(下单模块使用)
        self._order_datetime = ''
        #最新交易时间戳(下单模块使用)
        self._order_timestamp = ''

        #tick交易数据
        self._trade = {}
        self._trade_tmp = {}
        #上一条tick交易数据
        self._pre_trade = {}
        #深度挂单数据
        self._quote = {}
        self._quote_tmp = {}
        #5档深度挂单数据
        self._quote5 = {}
        #订单数据
        self._order = {}
        self._order_realtime_price_volume = {}
        #持仓数据
        self._position = {}
        self._position_detail = {}
        #1分钟数据 
        self._trade_m1 = {}
        self._trade_m1_tmp = {}
        #每分钟计数
        self._minute_num = 0 
        #n分钟合成数据
        self._trade_mn = {}
        #用于合成15分钟数据的1分钟临时数据
        self._trade_m1_tmp_m15 = {}
        #15分钟合成数据
        self._trade_m15 = {}
        #下单状态:1.卖单挂单sell_resting_order,2.卖单追单sell_after_order,3.买单挂单buy_resting_order,4.买单追单buy_after_order,5.取消订单cancel_order
        self._order_status = ''
        #-----------------------0.交易开始时间
        self._start_timestamp = c.MAX_TIMESTAMP
        #-----------------------1.卖挂单时间
        self._sell_resting_order_timestamp = c.MAX_TIMESTAMP
        #1-1.实时卖挂单时间
        self._realtime_sell_resting_order_timestamp = c.MAX_TIMESTAMP 
        #-----------------------2.卖追单时间
        self._sell_after_order_timestamp = c.MAX_TIMESTAMP
        self._sell_after_order_timestamp_add = c.SELL_AFTER_ORDER_TIMESTAMP_ADD
        self._sell_after_order_timestamp_add_15min = c.SELL_AFTER_ORDER_TIMESTAMP_ADD_15MIN
        #2-1.卖实时追单时间
        self._realtime_sell_after_order_timestamp = c.MAX_TIMESTAMP 
        self._realtime_sell_after_order_timestamp_add = c.REALTIME_SELL_AFTER_ORDER_TIMESTAMP_ADD 
        self._realtime_sell_after_order_timestamp_add_15min = c.REALTIME_SELL_AFTER_ORDER_TIMESTAMP_ADD_15MIN 
        #3.买挂单时间
        self._buy_resting_order_timestamp = c.MAX_TIMESTAMP 
        #3-1.实时买挂单时间
        self._realtime_buy_resting_order_timestamp = c.MAX_TIMESTAMP 
        #4.买追单时间
        self._buy_after_order_timestamp = c.MAX_TIMESTAMP 
        self._buy_after_order_timestamp_add = c.BUY_AFTER_ORDER_TIMESTAMP_ADD  
        self._buy_after_order_timestamp_add_15min = c.BUY_AFTER_ORDER_TIMESTAMP_ADD_15MIN 
        #4-1.买实时追单时间
        self._realtime_buy_after_order_timestamp = c.MAX_TIMESTAMP 
        self._realtime_buy_after_order_timestamp_add = c.REALTIME_BUY_AFTER_ORDER_TIMESTAMP_ADD 
        self._realtime_buy_after_order_timestamp_add_15min = c.REALTIME_BUY_AFTER_ORDER_TIMESTAMP_ADD_15MIN 
        #5.取消订单时间
        self._cancel_order_timestamp = c.MAX_TIMESTAMP 
        self._cancel_order_timestamp_add = c.CANCEL_ORDER_TIMESTAMP_ADD 
        self._cancel_order_timestamp_add_15min = c.CANCEL_ORDER_TIMESTAMP_ADD_15MIN 
        #目标字段
        self.MBAR_HEADER = ['datetime', 'symbol', 'open', 'high', 'low', 'close', 'vol']
        self.MBAR_HEADER_MA = ['datetime', 'symbol', 'open', 'high', 'low', 'close', 'vol', 'ma40']
        #OKEX接收字段
        self.OKEX_MBAR_HEADER = ['datetime', 'symbol', 'open', 'high', 'low', 'close', 'vol']

        #需要把继承父类的初始化放在子类初始化最后
        Websocket.__init__(self, endPoint, symbol, apiKey, apiSecret, passphrase)

    #消息驱动
    def _on_message(self, message):
        #
        message = inflate(message)
        #self.logger.debug('message: %s-%s',message,type(message))

        '''Handler for parsing WS messages.'''
        #self.logger.setLevel(logging.DEBUG)  # Change this to DEBUG if you want a lot more info
        #pre_result = {}
        if type(message) == bytes :
            #if 'pong' in message :
            #    pdb.set_trace()
            #result = message
            result = str(message, encoding = "utf8") 
            if 'pong' in result:
                result = result
                #self.logger.debug('pong:%s,%s,%s' %(result,server_timestamp(),int(server_timestamp())))
            else :
                result = json.loads(result)
            self.logger.debug('result:%s',result)

            '''
                try:

                    if ('tick' in result) and ('data' in result['tick']):
                        if (result['ch'] in pre_result) and ('tick' in pre_result[result['ch']]) and result == pre_result[result['ch']]:
                            self.logger.info('完全重复结果: \r\n%s\r\n%s',result,pre_result[result['ch']])
                            return 
                        elif (result['ch'] in pre_result) and ('tick' in pre_result[result['ch']]) and result['tick'] == pre_result[result['ch']]['tick']:
                            self.logger.info('Tick重复结果: \r\n%s\r\n%s',result,pre_result[result['ch']])
                            return 
                        #elif (result['ch'] in pre_result) and ('tick' in pre_result[result['ch']]) and result['tick']['ts'] < pre_result[result['ch']]['tick']['ts']:
                        #    self.logger.info('小于前一条时间: \r\n%s\r\n%s',result,pre_result[result['ch']])
                        #    continue 
                        else :
                            pre_result[result['ch']] = result
                except Exception as re:
                    print('检测出异常{}'.format(re))
                    return
            '''
            message = result
        else :
            self.logger.info('error: %s,%s' %(type(message),str(message)))

        #数据处理模块
        self._get_trade_data(message)

        #模型下单模块
        self._model_order(message)
        #threading.Thread(target=self._model_order(message))

    #模型下单模块
    def _model_order(self, message) :
        #trade detail-交易数据
        #{'instrument_id': 'BTC-USDT', 'price': '5133.1', 'side': 'sell', 'size': '0.02394361', 'timestamp': '2019-04-15T09:22:59.484Z', 'trade_id': '1315460352'}
        #交易数据驱动模型
        if ('table' in message) and (message['table'] == 'spot/trade') and ('data' in message):
            for v in message['data']:
                if 'instrument_id' in v :
                    m_symbol = v['instrument_id'] 
                    #判断每分钟开始时刻执行
                    m_datetime = v['timestamp'][0:10]+" "+v['timestamp'][11:19]
                    #处理订阅数据出现后条时间币前一条小情况
                    if self._order_pre_time != '' and m_datetime < self._order_pre_time :
                        self.logger.debug('Tick-trade detail-insert error data:%s-%s-%s' % (message,m_datetime,self._order_pre_time))
                        m_datetime = self._order_pre_time
                    m_timestamp = int(time.mktime(time.strptime(m_datetime, "%Y-%m-%d %H:%M:%S")))
                    #最新交易时间(下单模块使用)
                    self._order_datetime = m_datetime 
                    #最新交易时间戳(下单模块使用)
                    self._order_timestamp = m_timestamp 
                    #if server_timestamp() :
                    #    self.logger.info('m_datetime,m_timestamp:%s-%s-%s' % (v['timestamp'],str(server_timestamp())[:10],m_timestamp))
                    #else :
                    self.logger.debug('m_datetime,m_timestamp:%s-%s' % (v['timestamp'],m_timestamp))
                    '''
                    #高频模型调仓-15分钟,判断窗口周期开始时刻执行close价调仓,增加self._trade_mn判断是过滤掉第一分钟未取历史数据情况
                    if self._order_pre_time != '' and ((int(m_datetime[11:13])*60+int(m_datetime[14:16]))%period_number_15min) == 0 and ((int(m_datetime[11:13])*60+int(m_datetime[14:16]))%period_number_15min) != ((int(self._order_pre_time[11:13])*60+int(self._order_pre_time[14:16]))%period_number_15min) and self._trade_m15:
                        self.logger.info('M%s nowtime - pertime: %s - %s' %(period_number_15min, m_datetime, self._order_pre_time))
                        #首先判断是否存在15分钟模型的配置和模型路径 
                        if cfg_path_15min and model_15min :
                            init_dict = hold_data_load()
                            logger.info('%s分钟初始化文件 %s' % (period_number_15min,init_dict))

                            #如果不存在初始化文件0值初始化
                            if not init_dict :
                                init_dict = {} 
                                init_dict['init_total'] = np.zeros((1,len(code_list))) 
                                init_dict['init_volume'] = np.zeros((1,len(code_list))) 
                                init_dict['init_open_avg'] = np.zeros((1,len(code_list)))
                                init_dict['init_open_avg'][0][0] = 1
                                init_dict['init_high_trade'] = np.zeros((1,len(code_list))) 
                                hold_data_open(init_dict)

                            #如果超过15分钟下单大于等于11次,0值初始化
                            if ('init_high_trade' in init_dict) and (init_dict['init_high_trade'][0][0] >= c.CHANGE_MODEL_NUMBER_15MIN) :
                                init_dict['init_high_trade'] = np.zeros((1,len(code_list))) 
                                hold_data_open(init_dict)
                        
                            #如果高频交易为首次0次,但BTC-USDT交易量大于1500,则取消当前所有订单重新下单
                            if ('init_high_trade' in init_dict) and (init_dict['init_high_trade'][0][0] == 0) and (self._trade_m15['BTC-USDT']['vol'].iloc[-1] > c.BTC_USDT_VOLUME_LIMIT) :
                                #获取未成交订单
                                spotAPI = spot.SpotAPI(apiKey, apiSecret, passphrase, True)
                                _open_orders = spotAPI.get_orders_pending('','','','')
                                #[[], {}]
                                #[[{"client_oid": "", "created_at": "2019-04-15T15:01:07.000Z", "filled_notional": "0", "filled_size": "0", "funds": "", "instrument_id": "BTC-USDT", "notional": "", "order_id": "2661054335628288", "order_type": "0", "price": "5120", "product_id": "BTC-USDT", "side": "buy", "size": "0.01192712", "status": "open", "timestamp": "2019-04-15T15:01:07.000Z", "type": "limit"}], {"before": "20837311351", "after": "20837311351"}]
                                self.logger.info('%s分钟模型切换%s分钟模型,查询所有当前帐号下未成交订单: %s' %(period_number, period_number_15min, _open_orders))
                                if (_open_orders) and (len(_open_orders[0]) > 0) :
                                    for val in _open_orders[0] :
                                        _symbol = val['instrument_id']
                                        _order_id = val['order_id']
                                        #取消未成交订单
                                        #{"client_oid": "", "error_code": 0, "error_message": {}, "order_id": "2661455656587264", "result": true}
                                        #{"code":33027,"message":"Order has been revoked or revoked"}, 400
                                        _cancel_open_orders = {}
                                        spotAPI = spot.SpotAPI(apiKey, apiSecret, passphrase, True)
                                        _cancel_open_orders = spotAPI.revoke_order(_order_id,_symbol)

                                        self.logger.info('%s分钟模型切换%s分钟模型,取消符合条件的订单: %s' %(period_number,period_number_15min, _cancel_open_orders))
                                    #根据历史成交订单,初始现金金额,持仓量,购买均价
                                    init_total_volume_avg()
                                    logger.info('$$$position$$$,%s,%s,%s' % (init_total,init_volume,init_open_avg))

                                    #判断存在上一次total数据:当前交易币种持仓-(除交易币种外的上一次各币种持仓折算交易币种额度的加和 + 交易币种持仓量) * 交易币种预留比例
                                    if sum(init_total[0][1:len(code_list)]) > 0 :
                                        init_total[0][0] = init_volume[0][0]-(sum(init_total[0][1:len(code_list)])+init_volume[0][0])*quote_currency_ratio
                                        logger.info('$$$position-auto$$$,%s,%s,%s' % (init_total,init_volume,init_open_avg))
                                    else :
                                        init_total[0][0] = init_volume[0][0]-300
                                        logger.info('$$$position-auto-no-total$$$,%s,%s,%s' % (init_total,init_volume,init_open_avg))

                            #首先判断高频交易当前执行次数大于等于1次小于等于11次范围内,继续按照15分钟执行,或者首次执行0次切BTC-USDT交易量大于1500
                            if (('init_high_trade' in init_dict) and (init_dict['init_high_trade'][0][0] >= 1) and (init_dict['init_high_trade'][0][0] <= c.CHANGE_MODEL_NUMBER_15MIN)) or (('init_high_trade' in init_dict) and (init_dict['init_high_trade'][0][0] == 0) and self._trade_m15['BTC-USDT']['vol'].iloc[-1] > c.BTC_USDT_VOLUME_LIMIT) :
                                self._order = {}
                                #1.卖挂单时间
                                self._sell_resting_order_timestamp = m_timestamp
                                #1-1.实时卖挂单时间
                                #self._realtime_sell_resting_order_timestamp = c.MAX_TIMESTAMP 
                                #2.卖追单时间
                                self._sell_after_order_timestamp = m_timestamp + self._sell_after_order_timestamp_add_15min
                                #2-1.卖实时追单时间
                                self._realtime_sell_after_order_timestamp = m_timestamp + self._realtime_sell_after_order_timestamp_add_15min
                                #3.买挂单时间
                                #self._buy_resting_order_timestamp = c.MAX_TIMESTAMP 
                                #3-1.实时买挂单时间
                                #self._realtime_buy_resting_order_timestamp = c.MAX_TIMESTAMP 
                                #4.买追单时间
                                self._buy_after_order_timestamp = m_timestamp + self._buy_after_order_timestamp_add_15min
                                #4-1.买实时追单时间
                                self._realtime_buy_after_order_timestamp = m_timestamp + self._realtime_buy_after_order_timestamp_add_15min
                                #5.取消订单时间
                                self._cancel_order_timestamp = m_timestamp + self._cancel_order_timestamp_add_15min

                                self.logger.info('self._sell_after_order_timestamp,self._buy_after_order_timestamp,self._cancel_order_timestamp: %s,%s,%s,%s' %(m_timestamp, self._sell_after_order_timestamp, self._buy_after_order_timestamp, self._cancel_order_timestamp) )
                                self.logger.info('处理模型输入%s分钟数据...' % period_number_15min)

                                #获取多品种交集矩阵-15分钟
                                df_mix_15min = get_mix_data(self._trade_m15,self.MBAR_HEADER) 
                                self.logger.debug('History df_mix_15min dict from symbol:\r\n %s' % df_mix_15min)

                                #数据输入模型
                                model_output(df_mix_15min) 
                                self.logger.debug('model_output _log_df.T :\r\n %s' %(_log_df.T))
                                
                                #增加15分钟高频交易计数
                                init_dict['init_high_trade'][0][0] += 1
                                init_dict['init_high_trade'][0][code_list.index('BTC-USDT')] = 1
                                hold_data_open(init_dict)

                            else :
                                self.logger.info('%s根%s分钟不执行...' %(window_size,period_number_15min))
                        else :
                            self.logger.info('%s根%s分钟无配置路径和模型路径...' %(window_size,period_number_15min))
                    '''
                    
                    #基础模型调仓-45分钟判断窗口周期开始时刻执行close价调仓,增加self._trade_mn判断是过滤掉第一分钟未取历史数据情况
                    if self._order_pre_time != '' and ((int(m_datetime[11:13])*60+int(m_datetime[14:16]))%period_number) == 0 and ((int(m_datetime[11:13])*60+int(m_datetime[14:16]))%period_number) != ((int(self._order_pre_time[11:13])*60+int(self._order_pre_time[14:16]))%period_number) and self._trade_mn:
                        self.logger.info('M%s nowtime - pertime: %s - %s' %(period_number, m_datetime, self._order_pre_time))
                        init_dict = hold_data_load()
                        logger.info('%s分钟初始化文件 %s' % (period_number,init_dict))
                        if not (init_dict and ('init_high_trade' in init_dict) and (init_dict['init_high_trade'][0][0] >= 1) and (init_dict['init_high_trade'][0][0] <= c.CHANGE_MODEL_NUMBER_15MIN)):
                            self._order = {}
                            self._start_timestamp = m_timestamp
                            #-----------------------1.卖挂单时间
                            self._sell_resting_order_timestamp = m_timestamp
                            #1-1.实时卖挂单和向前调整挂单时间
                            self._realtime_sell_resting_order_timestamp = c.MAX_TIMESTAMP 
                            #-----------------------2.卖追单时间
                            self._sell_after_order_timestamp = m_timestamp + self._sell_after_order_timestamp_add
                            #2-1.卖实时追单时间
                            self._realtime_sell_after_order_timestamp = m_timestamp + self._realtime_sell_after_order_timestamp_add
                            #-----------------------3.买挂单时间
                            self._buy_resting_order_timestamp = m_timestamp 
                            #3-1.实时买挂单时间
                            self._realtime_buy_resting_order_timestamp = c.MAX_TIMESTAMP 
                            #3-3.实时买挂单向后调整挂单时间
                            self._realtime_buy_resting_order_back_timestamp = c.MAX_TIMESTAMP 
                            #-----------------------4.买追单时间
                            self._buy_after_order_timestamp = m_timestamp + self._buy_after_order_timestamp_add
                            #4-1.买实时追单时间
                            self._realtime_buy_after_order_timestamp = m_timestamp + self._realtime_buy_after_order_timestamp_add
                            #-----------------------5.取消订单时间
                            self._cancel_order_timestamp = m_timestamp + self._cancel_order_timestamp_add

                            self.logger.info('self._sell_after_order_timestamp,self._buy_after_order_timestamp,self._cancel_order_timestamp: %s,%s,%s,%s' %(m_timestamp, self._sell_after_order_timestamp, self._buy_after_order_timestamp, self._cancel_order_timestamp) )
                            self.logger.info('处理模型输入%s分钟数据...' % period_number)

                            #获取多品种交集矩阵-45分钟
                            df_mix = get_mix_data(self._trade_mn,self.MBAR_HEADER_MA) 
                            self.logger.debug('History df_mix dict from symbol:\r\n %s' % df_mix)

                            #数据输入模型
                            model_output(df_mix) 
                            self.logger.debug('model_output _log_df.T :\r\n %s' %(_log_df.T))

                        else :
                            self.logger.info('%s根%s分钟不执行...' %(window_size,period_number))
                    
                    #1.卖单挂单-当前仅出现一次,分单当前放在实时卖挂单进行处理
                    if m_timestamp >= self._sell_resting_order_timestamp :
                        tmp_start_timestamp_1 = int(str(server_timestamp())[:10])

                        #根据变化资金交易手数为正开仓信号计成本，为负平仓信号计收益
                        #先平仓，1、close价格平仓，2、3秒钟未成交撤单，3、对手价平仓，4、马上未成交撤单，5、再用close价格平仓
                        #再开仓，1、判断盘口，对手价如小于或等于close价，对手价下单，否则close价格下单
                        #1、close价格为基准策略卖出
                        #下单状态:卖单挂单sell_resting_order,卖单追单sell_after_order,买单挂单buy_resting_order,买单追单buy_after_order,取消订单cancel_order
                        self._order_status = 'sell_resting_order'
                        self.logger.info('-----------1.卖单所有币种挂单-开始-%s-------------' %(self._order_status))
                        _symbol = ''
                        _order_side = 'sell'
                        self._resting_single_module(m_timestamp, _symbol, _order_side) 

                        tmp_end_timestamp_1 = int(str(server_timestamp())[:10])
                        if (tmp_end_timestamp_1-tmp_start_timestamp_1 > 0) and (tmp_end_timestamp_1-tmp_start_timestamp_1 < c.REALTIME_SELL_RESTING_ORDER_INTERVAL_TIMESTAMP):
                            self._realtime_sell_resting_order_timestamp = m_timestamp+tmp_end_timestamp_1-tmp_start_timestamp_1+c.REALTIME_SELL_RESTING_ORDER_INTERVAL_TIMESTAMP
                        else :
                            self._realtime_sell_resting_order_timestamp = m_timestamp+c.REALTIME_SELL_RESTING_ORDER_INTERVAL_TIMESTAMP
                        self.logger.info('-----------1.卖单所有币种挂单-完成-self._sell_resting_order_timestamp,m_timestamp,tmp_end_timestamp_1,tmp_start_timestamp_1,self._realtime_sell_resting_order_timestamp-%s,%s,%s,%s,%s--------------' %(self._sell_resting_order_timestamp,m_timestamp,tmp_end_timestamp_1,tmp_start_timestamp_1,self._realtime_sell_resting_order_timestamp))
                        self._sell_resting_order_timestamp = c.MAX_TIMESTAMP 

                    #1-1.卖单实时挂单:realtime_sell_resting_order,大于实时卖挂单设定时间,卖挂单阶段已完成
                    if (m_timestamp >= self._realtime_sell_resting_order_timestamp) and (self._sell_resting_order_timestamp == c.MAX_TIMESTAMP) :
                        tmp_start_timestamp_1_1 = int(str(server_timestamp())[:10])
                        tmp_realtime_sell_resting_order_timestamp_1_1 = copy.deepcopy(self._realtime_sell_resting_order_timestamp)
                        #判断1.卖挂单已经完全成交,则停止判断是否实时挂单,2.大于买卖追单时间,则停止判断是否实时挂单self._buy_after_order_timestamp
                        #1.判断根据取整后目标调仓量为卖出调仓(负值)的对应当前未成交量的绝对值后相加大于最小调仓量0.001;
                        #2.判断在买卖单挂单和卖追单阶段
                        if ('floor_change_volume' in _log_df) and ('realtime_nofilled_volume' in _log_df) and ((abs(_log_df.realtime_nofilled_volume[_log_df.floor_change_volume<0].fillna(0)).sum()) > 0.001) and (self._order_status == 'sell_resting_order' or self._order_status == 'sell_after_order' or self._order_status == 'buy_resting_order' ) :
                            #self._order_status = 'realtime_sell_resting_order'
                            self.logger.info('-----------1-0.卖单实时挂单-开始-%s,%s--------------' %(m_timestamp,self._realtime_sell_resting_order_timestamp))
                            #卖单实时挂单,判断根据取整后目标调仓量为卖出调仓(负值)的对应当前开仓的绝对值相加大于最小调仓量0.001
                            if ('realtime_noopen_volume' in _log_df) and ((abs(_log_df.realtime_noopen_volume[_log_df.floor_change_volume<0].fillna(0)).sum()) > 0.001) :
                                self.logger.info('-----------1-1.卖单实时挂单-处理未下单-开始--------------')
                                for i_1_1 in list(range(len(_log_df['realtime_noopen_volume']))) : 
                                    _symbol_1_1 = _log_df['realtime_noopen_volume'].index[i_1_1]
                                    #不等于usdt,选出调仓量小于0的卖单处理
                                    if (_symbol_1_1 != quote_currency) and ('output_change_volume' in _log_df) and (_symbol_1_1 in _log_df['output_change_volume']) and (_log_df['output_change_volume'][_symbol_1_1] < 0) :
                                        #理论调仓量按照系统要求保留位数舍去取整(正数舍去,负数的绝对值为进1取整)
                                        _volume_1_1 = math.floor(_log_df['realtime_noopen_volume'][_symbol_1_1]*(10**init_precision[_symbol_1_1]['vol'])+0.1)/(10**init_precision[_symbol_1_1]['vol'])
                                        #判断volume是否大于最小值
                                        if abs(_volume_1_1) < float(init_precision[_symbol_1_1]['min_vol']) :
                                            _volume_1_1 = 0

                                        #卖单挂单未挂单
                                        if _volume_1_1 < 0 :
                                            self.logger.info('-----------1-1.存在实时未下单_symbol,realtime_noopen_volume-%s,%s--------------' %(_symbol_1_1,_volume_1_1))
                                            _order_side = 'sell'
                                            self._realtime_resting_single_module(m_timestamp, _symbol_1_1, _order_side) 
                                        elif _volume_1_1 > 0 :
                                            self.logger.info('-----------1-1.存在实时未下单错误error_symbol,realtime_noopen_volume-%s,%s--------------' %(_symbol_1_1,_volume_1_1))
                            else :
                                self.logger.info('-----------1-1.卖单实时挂单-处理未下单-完成-不存在实时未下单数据--------------')

                            #卖单实时挂单,通过下单未成交判断各币种是否进行位置调整
                            if ('realtime_open_nofilled_volume' in _log_df) and ((abs(_log_df.realtime_open_nofilled_volume[_log_df.floor_change_volume<0].fillna(0)).sum()) > 0.001) :
                                self.logger.info('-----------1-2.卖单实时挂单-挂单位置调整-开始-促进成交向前调价--------------')
                                for i_1_2 in list(range(len(_log_df['realtime_open_nofilled_volume']))) : 
                                    _symbol_1_2 = _log_df['realtime_open_nofilled_volume'].index[i_1_2]
                                    #不等于usdt,选出调仓量小于0的卖单处理
                                    if (_symbol_1_2 != quote_currency) and ('output_change_volume' in _log_df) and (_symbol_1_2 in _log_df['output_change_volume']) and (_log_df['output_change_volume'][_symbol_1_2] < 0) :
                                        #理论调仓量按照系统要求保留位数舍去取整(正数舍去,负数的绝对值为进1取整)
                                        _volume_1_2 = math.floor(_log_df['realtime_open_nofilled_volume'][_symbol_1_2]*(10**init_precision[_symbol_1_2]['vol'])+0.1)/(10**init_precision[_symbol_1_2]['vol'])

                                        #判断volume是否大于最小值
                                        if abs(_volume_1_2) < float(init_precision[_symbol_1_2]['min_vol']) :
                                            _volume_1_2 = 0

                                        #卖单挂单下单未成交
                                        if _volume_1_2 < 0 :
                                            self.logger.info('-----------1-2.存在实时下单未成交_symbol,realtime_open_nofilled_volume-%s,%s--------------' %(_symbol_1_2,_volume_1_2))
                                            _order_side = 'sell'
                                            #调仓方向:空无方向默认向前,front向前调仓,back向后调仓
                                            _direction = 'front'
                                            self._realtime_resting_single_position_module(m_timestamp, _symbol_1_2, _order_side, _direction)
                                        elif _volume_1_2 > 0 :
                                            self.logger.info('-----------1-2.存在实时下单未成交错误error_symbol,realtime_noopen_volume-%s,%s' %(_symbol_1_2,_volume_1_2))
                            else :
                                self.logger.info('-----------1-2.卖单实时挂单-挂单位置调整-不存在下单未成交数据--------------')

                            tmp_end_timestamp_1_1 = int(str(server_timestamp())[:10])
                            if (tmp_end_timestamp_1_1-tmp_start_timestamp_1_1 > 0) and (tmp_end_timestamp_1_1-tmp_start_timestamp_1_1 < c.REALTIME_SELL_RESTING_ORDER_INTERVAL_TIMESTAMP):
                                #间隔10秒实时卖挂单1次
                                self._realtime_sell_resting_order_timestamp = m_timestamp+tmp_end_timestamp_1_1-tmp_start_timestamp_1_1+c.REALTIME_SELL_RESTING_ORDER_INTERVAL_TIMESTAMP
                                self._realtime_buy_resting_order_timestamp = m_timestamp+c.REALTIME_BUY_RESTING_ORDER_INTERVAL_TIMESTAMP-1
                            else :
                                self._realtime_sell_resting_order_timestamp = m_timestamp+c.REALTIME_SELL_RESTING_ORDER_INTERVAL_TIMESTAMP
                                self._realtime_buy_resting_order_timestamp = m_timestamp+c.REALTIME_BUY_RESTING_ORDER_INTERVAL_TIMESTAMP-1
                            self.logger.info('-----------1-0.卖单实时挂单-完成tmp_realtime_sell_resting_order_timestamp_1_1,m_timestamp,tmp_end_timestamp_1_1,tmp_start_timestamp_1_1,self._realtime_sell_resting_order_timestamp-%s,%s,%s,%s,%s--------------' %(tmp_realtime_sell_resting_order_timestamp_1_1,m_timestamp,tmp_end_timestamp_1_1,tmp_start_timestamp_1_1,self._realtime_sell_resting_order_timestamp))
                        elif ('floor_change_volume' in _log_df) and ('realtime_nofilled_volume' in _log_df) and ((abs(_log_df.realtime_nofilled_volume[_log_df.floor_change_volume<0].fillna(0)).sum()) <= 0.001) and (self._order_status == 'sell_resting_order' or self._order_status == 'sell_after_order' or self._order_status == 'buy_resting_order' ) :
                            self.logger.info('-----------1-0.卖单实时挂单-已完全成交或少量未成交')
                            self._realtime_sell_resting_order_timestamp = c.MAX_TIMESTAMP 
                        else :
                            self.logger.info('-----------1-0.卖单实时挂单-未知错误待排查')
                            self._realtime_sell_resting_order_timestamp = c.MAX_TIMESTAMP 

                    #2.卖单追单,进入方式1.卖单挂单所有币种不调仓直接跳到
                    if m_timestamp >= self._sell_after_order_timestamp :
                        self._order_status = 'sell_after_order'
                        tmp_sell_after_order_timestamp_2 = copy.deepcopy(self._sell_after_order_timestamp)
                        #下单状态:卖单挂单sell_resting_order,卖单追单sell_after_order,买单挂单buy_resting_order,买单追单buy_after_order,取消订单cancel_order
                        self.logger.info('-----------2.卖单追单-%s,%s-------------' %(m_timestamp,self._sell_after_order_timestamp))
                        self.logger.info('M+%s %s nowtime - pertime: %s - %s' %(self._sell_after_order_timestamp_add/60, self._order_status, m_datetime, self._order_pre_time))

                        #第1次追单
                        _open_orders = self._after_single_module(m_timestamp, 1, '','sell')

                        #第2次追单,判断成功取消订单量大于0
                        if (_open_orders) and len(_open_orders[0]) > 0 :
                            sleep(2)
                            _open_orders = self._after_single_module(m_timestamp, 2, '','sell')

                        self._sell_after_order_timestamp = c.MAX_TIMESTAMP
                        self._buy_resting_order_timestamp = m_timestamp 
                        self.logger.info('-----------2.卖单追单-完成-%s,%s,%s,%s--------------' %(tmp_sell_after_order_timestamp_2,m_timestamp,self._sell_after_order_timestamp,self._buy_resting_order_timestamp))

                        #get_orders_pending-获取未成交订单
                        #[[], {}]
                        #[[{"client_oid": "", "created_at": "2019-04-15T15:01:07.000Z", "filled_notional": "0", "filled_size": "0", "funds": "", "instrument_id": "BTC-USDT", "notional": "", "order_id": "2661054335628288", "order_type": "0", "price": "5120", "product_id": "BTC-USDT", "side": "buy", "size": "0.01192712", "status": "open", "timestamp": "2019-04-15T15:01:07.000Z", "type": "limit"}], {"before": "20837311351", "after": "20837311351"}]
                        #参数名	类型	描述
                        #from	String	[非必填] 请求此id之后(更新的数据)的分页内容（举例一列数：1，2，3，4，5。from 4 只有5，to 4有1，2，3）
                        #to	String	[非必填] 请求此id之前(更旧的数据)的分页内容
                        #limit	String	[非必填] 分页返回的结果集数量，默认为100，最大为100(具体参见分页处的描述)
                        #instrument_id	String	[非必填]币对名称 不填时返回所有未成交订单
                        #返回参数
                        #参数名	类型	描述
                        #order_id	String	订单ID
                        #client_oid	String	用户设置的订单ID
                        #price	String	价格
                        #size	String	交易货币数量
                        #notional	String	买入金额，市价买入时返回
                        #instrument_id	String	币对名称
                        #side	String	buy or sell
                        #type	String	limit,market(默认是limit)
                        #timestamp	String	订单创建时间
                        #filled_size	String	已成交数量
                        #filled_notional	String	已成交金额
                        #status	String	订单状态(all:所有状态 open:未成交 part_filled:部分成交 canceling:撤销中 filled:已成交 cancelled:已撤销 ordering:下单中,failure：下单失败 )
                        #解释说明
                        #client_oid 的类型为字母（大小写）+数字或者纯字母类型 ，1-32位字符 ，用户需要自己保证此ID不重复，我方不会进行排重提示，如有重复，查询订单时只能查询出最新的一条数据。
                        #本接口只能查询所有未成交或者部分成交的订单
                        #未成交的订单可能会根据市场情况在你发起请求和服务器响应之间改变状态。

                    #3.买单挂单-全量买单当前不出现-分单当前不出现
                    if m_timestamp >= self._buy_resting_order_timestamp :
                        tmp_buy_resting_order_timestamp_3 = copy.deepcopy(self._buy_resting_order_timestamp)
                        tmp_start_timestamp_3 = int(str(server_timestamp())[:10])
                        self._order_status = 'buy_resting_order'
                        self.logger.info('-----------3.买单挂单-%s,%s-------------' %(m_timestamp,self._buy_resting_order_timestamp))
                        #self._resting_single_module(m_timestamp, '', 'buy')
                        self._realtime_resting_single_module(m_timestamp, '', 'buy')

                        tmp_end_timestamp_3 = int(str(server_timestamp())[:10])
                        if (tmp_end_timestamp_3-tmp_start_timestamp_3 > 0) and (tmp_end_timestamp_3-tmp_start_timestamp_3 < c.REALTIME_BUY_RESTING_ORDER_INTERVAL_TIMESTAMP):
                            self._realtime_buy_resting_order_timestamp = m_timestamp+tmp_end_timestamp_3-tmp_start_timestamp_3+c.REALTIME_BUY_RESTING_ORDER_INTERVAL_TIMESTAMP
                        else :
                            self._realtime_buy_resting_order_timestamp = m_timestamp+c.REALTIME_BUY_RESTING_ORDER_INTERVAL_TIMESTAMP 
                        self.logger.info('-----------3.买单挂单-完成-%s,%s,%s,%s,%s,%s--------------' %(tmp_buy_resting_order_timestamp_3,m_timestamp,tmp_end_timestamp_3,tmp_start_timestamp_3,self._buy_resting_order_timestamp,self._realtime_buy_resting_order_timestamp))
                        self._buy_resting_order_timestamp = c.MAX_TIMESTAMP

                    #3-1.买单实时挂单:realtime_buy_resting_order
                    if m_timestamp >= self._realtime_buy_resting_order_timestamp :
                        tmp_realtime_buy_resting_order_timestamp_3_1 = copy.deepcopy(self._realtime_buy_resting_order_timestamp)
                        tmp_start_timestamp_3_1 = int(str(server_timestamp())[:10])
                        #判断1.买挂单已经完全成交,则停止判断是否实时挂单,2.大于买卖追单时间,则停止判断是否实时挂单self._buy_after_order_timestamp
                        self.logger.info('-----------3-0.买单实时挂单-%s,%s--------------' %(m_timestamp,self._realtime_buy_resting_order_timestamp))
                        #条件是未完全成交且阶段不为买追单/取消订单
                        if ('floor_change_volume' in _log_df) and ('realtime_change_volume' in _log_df) and ((abs(_log_df.floor_change_volume[_log_df.floor_change_volume>0].sub(_log_df.realtime_change_volume).fillna(0)).sum()) > 0.001) and (self._order_status == 'sell_resting_order' or self._order_status == 'sell_after_order' or self._order_status == 'buy_resting_order' ) :
                            if ('floor_change_volume' in _log_df) and ('realtime_noopen_volume' in _log_df) and ((abs(_log_df.realtime_noopen_volume[_log_df.floor_change_volume>0].fillna(0)).sum()) > 0.001) :
                                self.logger.info('-----------3-1.买单实时挂单-处理未下单--------------')
                                self._realtime_resting_single_module(m_timestamp, '', 'buy') 
                            else :
                                self.logger.info('-----------3-1.买单实时挂单-不存在实时未挂单--------------')

                            #买单实时挂单,通过下单未成交判断各币种是否进行位置调整
                            if ('floor_change_volume' in _log_df) and ('realtime_open_nofilled_volume' in _log_df) and ((abs(_log_df.realtime_open_nofilled_volume[_log_df.floor_change_volume>0].fillna(0)).sum()) > 0.001) :
                                self.logger.info('-----------3-2.买单实时挂单-挂单位置调整-促进成交向前调成--------------')
                                for i_3_2 in list(range(len(_log_df['realtime_open_nofilled_volume']))) : 
                                    _symbol_3_2 = _log_df['realtime_open_nofilled_volume'].index[i_3_2]
                                    #不等于usdt,选出调仓量大于0的买单处理
                                    if (_symbol_3_2 != quote_currency) and ('output_change_volume' in _log_df) and (_symbol_3_2 in _log_df['output_change_volume']) and (_log_df['output_change_volume'][_symbol_3_2] > 0) :
                                        #理论调仓量按照系统要求保留位数舍去取整(正数舍去,负数的绝对值为进1取整)
                                        _volume_3_2 = math.floor(_log_df['realtime_open_nofilled_volume'][_symbol_3_2]*(10**init_precision[_symbol_3_2]['vol'])+0.1)/(10**init_precision[_symbol_3_2]['vol'])

                                        #判断volume是否大于最小值
                                        if abs(_volume_3_2) < float(init_precision[_symbol_3_2]['min_vol']) :
                                            _volume_3_2 = 0

                                        #买单挂单下单未成交
                                        if _volume_3_2 > 0 :
                                            self.logger.info('-----------3-2.存在实时下单未成交_symbol,realtime_open_nofilled_volume-%s,%s--------------' %(_symbol_3_2,_volume_3_2))
                                            _order_side = 'buy'
                                            #调仓方向:空无方向默认向前,front向前调仓,back向后调仓
                                            _direction = 'front'
                                            self._realtime_resting_single_position_module(m_timestamp, _symbol_3_2, _order_side, _direction)
                                        elif _volume_3_2 < 0 :
                                            self.logger.info('-----------3-2.存在实时下单未成交错误error_symbol,realtime_noopen_volume-%s,%s' %(_symbol_3_2,_volume_3_2))
                                        else :
                                            self.logger.info('-----------3-2.已下单未成交交易量为0-_symbol,realtime_noopen_volume-%s,%s' %(_symbol_3_2,_volume_3_2))
                            else :
                                self.logger.info('-----------3-2.买单实时挂单-挂单位置调整-不存在下单未成交数据--------------')

                            tmp_end_timestamp_3_1 = int(str(server_timestamp())[:10])
                            if (tmp_end_timestamp_3_1-tmp_start_timestamp_3_1 > 0) and (tmp_end_timestamp_3_1-tmp_start_timestamp_3_1 < c.REALTIME_BUY_RESTING_ORDER_INTERVAL_TIMESTAMP):
                                #间隔N秒实时卖挂单1次
                                self._realtime_buy_resting_order_timestamp = m_timestamp+tmp_end_timestamp_3_1-tmp_start_timestamp_3_1+c.REALTIME_BUY_RESTING_ORDER_INTERVAL_TIMESTAMP
                                self._realtime_sell_resting_order_timestamp = m_timestamp+c.REALTIME_SELL_RESTING_ORDER_INTERVAL_TIMESTAMP-1
                                #random.randint(10, 20) 
                            else :
                                self._realtime_buy_resting_order_timestamp = m_timestamp+c.REALTIME_BUY_RESTING_ORDER_INTERVAL_TIMESTAMP 
                                self._realtime_sell_resting_order_timestamp = m_timestamp+c.REALTIME_SELL_RESTING_ORDER_INTERVAL_TIMESTAMP-1
                            self.logger.info('-----------3-0.买单实时挂单-完成-%s,%s,%s,%s,%s--------------' %(tmp_realtime_buy_resting_order_timestamp_3_1,m_timestamp,tmp_end_timestamp_3_1,tmp_start_timestamp_3_1,self._realtime_buy_resting_order_timestamp))
                        else :
                            self.logger.info('买单实时挂单已完成或超过买单追单时间-(abs(_log_df.floor_change_volume[_log_df.floor_change_volume<0].sub(_log_df.realtime_change_volume).fillna(0)).sum()),self._realtime_sell_resting_order_timestamp,self._buy_after_order_timestamp)-%s,%s,%s' %((abs(_log_df.floor_change_volume[_log_df.floor_change_volume<0].sub(_log_df.realtime_change_volume).fillna(0)).sum()),self._realtime_sell_resting_order_timestamp,self._buy_after_order_timestamp))
                            self._realtime_buy_resting_order_timestamp = c.MAX_TIMESTAMP 

                    #4.再次买卖对手价追单成交时间 
                    if m_timestamp >= self._buy_after_order_timestamp :
                        self._order_status = 'buy_after_order'
                        self.logger.info('-----------4.买+卖单追单-%s-------------' %(self._order_status))
                        self.logger.info('M+%s time_make_order nowtime - pertime: %s - %s' % (self._buy_after_order_timestamp_add/60, m_datetime, self._order_pre_time))
                        #下单状态:卖单挂单sell_resting_order,卖单追单sell_after_order,买单挂单buy_resting_order,买单追单buy_after_order,取消订单cancel_order

                        #get_orders_pending(self, froms, to, limit, instrument_id):
                        #参数名	类型	描述
                        #from	String	[非必填] 请求此id之后(更新的数据)的分页内容（举例一列数：1，2，3，4，5。from 4 只有5，to 4有1，2，3）
                        #to	String	[非必填] 请求此id之前(更旧的数据)的分页内容
                        #limit	String	[非必填] 分页返回的结果集数量，默认为100，最大为100(具体参见分页处的描述)
                        #instrument_id	String	[非必填]币对名称 不填时返回所有未成交订单                        
                        #[[{"client_oid": "", "created_at": "2019-04-11T12:35:54.000Z", "filled_notional": "0", "filled_size": "0", "funds": "", "instrument_id": "BTC-USDT", "notional": "", "order_id": "2637834078521345", "order_type": "0", "price": "5120", "product_id": "BTC-USDT", "side": "sell", "size": "0.01", "status": "open", "timestamp": "2019-04-11T12:35:54.000Z", "type": "limit"}, {"client_oid": "", "created_at": "2019-04-11T12:13:32.000Z", "filled_notional": "0", "filled_size": "0", "funds": "", "instrument_id": "BTC-USDT", "notional": "", "order_id": "2637746160013312", "order_type": "0", "price": "5120", "product_id": "BTC-USDT", "side": "sell", "size": "0.01", "status": "open", "timestamp": "2019-04-11T12:13:32.000Z", "type": "limit"}], {"before": "20521459699", "after": "20519838193"}]
                        #参数名	类型	描述
                        #order_id	String	订单ID
                        #client_oid	String	用户设置的订单ID
                        #price	String	价格
                        #size	String	交易货币数量
                        #notional	String	买入金额，市价买入时返回
                        #instrument_id	String	币对名称
                        #side	String	buy or sell
                        #type	String	limit,market(默认是limit)
                        #timestamp	String	订单创建时间
                        #filled_size	String	已成交数量
                        #filled_notional	String	已成交金额
                        #status	String	订单状态(all:所有状态 open:未成交 part_filled:部分成交 canceling:撤销中 filled:已成交 cancelled:已撤销 ordering:下单中,failure：下单失败 )
                        #解释说明
                        #client_oid 的类型为字母（大小写）+数字或者纯字母类型 ，1-32位字符 ，用户需要自己保证此ID不重复，我方不会进行排重提示，如有重复，查询订单时只能查询出最新的一条数据。
                        #本接口只能查询所有未成交或者部分成交的订单
                        #未成交的订单可能会根据市场情况在你发起请求和服务器响应之间改变状态。                        

                        #第1次追单
                        _open_orders = self._after_single_module(m_timestamp, 1, '','') 
                            
                        #第2次追单,判断成功取消订单量大于0
                        if (_open_orders) and len(_open_orders[0]) > 0 :
                            sleep(10)
                            _open_orders = self._after_single_module(m_timestamp, 2, '','') 

                        if ('floor_change_volume' in _log_df) and ('realtime_change_volume' in _log_df) and ((abs(_log_df.floor_change_volume[_log_df.floor_change_volume>0].sub(_log_df.realtime_change_volume).fillna(0)).sum()) > 0.001) : 
                            self.logger.info('-----------4-2.卖单追单后进行买单挂单-%s-------------' %(m_timestamp))
                            self._realtime_resting_single_module(m_timestamp, '', 'buy')
                            sleep(10)
                            _open_orders = self._after_single_module(m_timestamp, 3, '','') 
                            
                        self._buy_after_order_timestamp = c.MAX_TIMESTAMP
                        self._sell_after_order_timestamp = c.MAX_TIMESTAMP
        
                    #5.取消未成交的挂单
                    if m_timestamp >= self._cancel_order_timestamp :
                        self._buy_after_order_timestamp = c.MAX_TIMESTAMP
                        self._sell_after_order_timestamp = c.MAX_TIMESTAMP
                        self._order_status = 'cancel_order'
                        self.logger.info('-----------5.取消所有订单-%s---------' %(self._order_status))
                        self.logger.info('M+%s nowtime - pertime: %s - %s' %(self._cancel_order_timestamp_add/60, m_datetime, self._order_pre_time))
                        #下单状态:卖单挂单sell_resting_order,卖单追单sell_after_order,买单挂单buy_resting_order,买单追单buy_after_order,取消订单cancel_order

                        _open_orders = []
                        _open_orders_n = 1
                        for symbol_o in symbol_list :
                            if (symbol_o != quote_currency) : 
                                #获取未成交订单
                                spotAPI = spot.SpotAPI(apiKey, apiSecret, passphrase, True)
                                _open_orders_s = spotAPI.get_orders_pending('','','',symbol_o)
                                if _open_orders_n == 1:
                                    if (_open_orders_s) :
                                        _open_orders = _open_orders_s[0]
                                else :
                                    if (_open_orders_s) :
                                        _open_orders = _open_orders + _open_orders_s[0]
                                _open_orders_n += 1
                        _open_orders = [_open_orders]

                        #[[], {}]
                        #[[{"client_oid": "", "created_at": "2019-04-15T15:01:07.000Z", "filled_notional": "0", "filled_size": "0", "funds": "", "instrument_id": "BTC-USDT", "notional": "", "order_id": "2661054335628288", "order_type": "0", "price": "5120", "product_id": "BTC-USDT", "side": "buy", "size": "0.01192712", "status": "open", "timestamp": "2019-04-15T15:01:07.000Z", "type": "limit"}], {"before": "20837311351", "after": "20837311351"}]
                        self.logger.info('M%s查询所有当前帐号下未成交订单: %s' %(self._cancel_order_timestamp_add/60, _open_orders[0]))
                        if (_open_orders) and (len(_open_orders[0]) > 0) :
                            #_revoke_order_params = []
                            #params = [{'instrument_id': 'BTC-USDT', 'order_ids':[3451042910179328, 3451042910179329]}]
                            for val in _open_orders[0] :
                                _symbol = val['instrument_id']
                                _order_id = val['order_id']
                                #取消未成交订单
                                #{"client_oid": "", "error_code": 0, "error_message": {}, "order_id": "2661455656587264", "result": true}
                                #{"code":33027,"message":"Order has been revoked or revoked"}, 400
                                _cancel_open_orders = {}
                                spotAPI = spot.SpotAPI(apiKey, apiSecret, passphrase, True)
                                _cancel_open_orders = spotAPI.revoke_order(_order_id,_symbol)

                                self.logger.info('M%s取消符合条件的订单: %s' %(self._cancel_order_timestamp_add/60, _cancel_open_orders))
    # params example:
    # [
    #   {"instrument_id":"btc-usdt","order_ids":[1600593327162368,1600593327162369]},
    #   {"instrument_id":"ltc-usdt","order_ids":[243464,234465]}
    # ]

                        #获取OKDK点卡信息
                        spotAPI = spot.SpotAPI(apiKey, apiSecret, passphrase, True)
                        point_result = spotAPI.get_ledger_record('OKDK', limit=1)
                        self.logger.info('point_result:%s' % (point_result))
                        if (point_result) and ('currency' in point_result[0]) and (point_result[0]['currency'] == 'OKDK') and ('balance' in point_result[0]) : 
                            self._position['OKDK'] = point_result[0]['balance'] 
                        else :
                            self._position['OKDK'] = 0

                        self.logger.info('Position dict:\r\n %s' % (self._position))
                        self.logger.info('Position_detail dict:\r\n %s' % (self._position_detail))
                        self.logger.info('order dict:\r\n %s' % (self._order))
                        #根据实际调仓成功计算
                        total_output(self._position,self._order) 
                        #_log_df.to_csv('./log/_log_df-'+m_datetime+'.csv')
                        self.logger.info('model detail:\r\n %s' % (_log_df.T))
                        #获取点卡账单
                        #[{"timestamp": "2019-04-17T17:15:13.000Z", "ledger_id": "4488343067", "created_at": "2019-04-17T17:15:13.000Z", "currency": "OKDK", "amount": "-0.01632987735", "balance": "68.746487932625", "type": "fee", "details": {"instrument_id": "ETH-USDT", "order_id": "2672905789639680", "product_id": "ETH-USDT"}}]
                        self.logger.info('datetime,output_total,cash_total,acount_total,hbpoint:\r\n %s,%s,%s,%s,%s' %(m_datetime,_log_df['output_total'].sum(),_log_df['output_volume'][quote_currency],_log_df['output_total'][1:].sum()+_log_df['output_volume'][quote_currency],self._position['OKDK']))
                        #固话初始化文件
                        init_dict = hold_data_load()
                        if init_dict :
                            init_dict['init_total'] = _log_df.output_total.values
                            init_dict['init_volume'] = _log_df.output_volume.values 
                            init_dict['init_open_avg'] = _log_df.now_open_avg.values
                        else :
                            init_dict = {}
                            init_dict['init_total'] = _log_df.output_total.values
                            init_dict['init_volume'] = _log_df.output_volume.values 
                            init_dict['init_open_avg'] = _log_df.now_open_avg.values

                        self.logger.info('init_dict:\r\n %s' % (init_dict))
                        hold_data_open(init_dict)

                        #根据历史成交订单,初始现金金额,持仓量,购买均价
                        init_total_volume_avg()
                        logger.info('$$$position$$$,%s,%s,%s' % (init_total,init_volume,init_open_avg))

                        #判断存在上一次total数据:当前交易币种持仓-(除交易币种外的上一次各币种持仓折算交易币种额度的加和 + 交易币种持仓量) * 交易币种预留比例
                        if sum(init_total[0][1:len(code_list)]) > 0 :
                            init_total[0][0] = init_volume[0][0]-(sum(init_total[0][1:len(code_list)])+init_volume[0][0])*quote_currency_ratio
                            logger.info('$$$position-auto$$$,%s,%s,%s' % (init_total,init_volume,init_open_avg))

                        self._cancel_order_timestamp = c.MAX_TIMESTAMP
                    
                    self._order_pre_time = m_datetime

        #depth step0-报价深度数据驱动
        #参数名	参数类型	描述
        #price	String	价格
        #size	String	数量
        #timestamp	String	时间戳
        #num_orders	String	组成此条深度的订单数量
        #instrument_id	String	币对
        #checksum	String	检验和
        #["411.8","10",8][price ,size ,num_orders]
        #{'table': 'spot/depth', 'action': 'update', 'data': [{'instrument_id': 'LTC-USDT', 'asks': [['82.08', '88.799226', 4], ['82.11', '0.677', 1], ['82.13', '8.076', 3], ['82.14', '16.050318', 5], ['82.15', '67.495073', 8], ['82.16', '16.818211', 7], ['82.17', '16.420122', 6], ['82.2', '107.999859', 5], ['82.21', '0.57104', 3], ['82.25', '57.925016', 3], ['82.3', '90.258635', 5]], 'bids': [['82.05', '0.66', 1], ['82.01', '22.77656', 8], ['82', '52.793909', 11], ['81.99', '5.611773', 9], ['81.98', '33.03742', 22], ['81.97', '35.013163', 13], ['81.96', '58.14296', 15], ['81.95', '7.056106', 10], ['81.93', '115.95094', 12], ['81.91', '12.650235', 6], ['81.88', '11.570018', 9], ['81.87', '15.916077', 6], ['81.86', '39.694619', 2], ['81.85', '36.955308', 4]], 'timestamp': '2019-04-15T09:32:51.209Z', 'checksum': 1680391679}]}
        elif ('table' in message) and (message['table'] == 'spot/depth') and ('data' in message):
            #下单状态:卖单挂单sell_resting_order,卖单追单sell_after_order,买单挂单buy_resting_order,买单追单buy_after_order,取消订单cancel_order
            self.logger.debug("bids-asks: %s" %(message))
            symbol = message['data'][0]['instrument_id']

            #########################################优化计划######################################
            #1.卖单保底追单,当成交价到close跌千5价格交易量小于成交量时，触发对手价追单。
            #X.当卖单挂单高于close价格,如果价格向下移动对手价时,实时追单吃对手单

            #判断每分钟开始时刻执行
            m_datetime = message['data'][0]['timestamp'][0:10]+" "+message['data'][0]['timestamp'][11:19]
            m_timestamp = int(time.mktime(time.strptime(m_datetime, "%Y-%m-%d %H:%M:%S")))

            #卖单实时追单-实时判断当成交价到close跌千5价格交易量小于成交量时，触发对手价追单,且只触发此币种1次实时追单
            if (self._order_status == 'sell_resting_order') and ('floor_change_volume' in _log_df) and (symbol in _log_df['floor_change_volume']) and (_log_df['floor_change_volume'][symbol] < 0) and ('now_close' in _log_df) and (symbol in _log_df['now_close']) and ('position_realtime_order' in _log_df) and (symbol in _log_df['position_realtime_order']) and (_log_df['position_realtime_order'][symbol] == 0) and (m_timestamp > self._realtime_sell_after_order_timestamp) :
                order_type = 'limit'
                order_side = 'sell'
                #理论调仓量按照系统要求保留位数舍去取整(正数舍去,负数的绝对值为进1取整)
                volume = _log_df['floor_change_volume'][symbol]
                #判断volume是否大于最小值
                if abs(volume) < float(init_precision[symbol]['min_vol']) :
                    volume = 0

                #close价格按照系统要求保留位数舍去取整
                now_close = math.floor(_log_df['now_close'][symbol]*(10**init_precision[symbol]['price'])+0.1)/(10**init_precision[symbol]['price'])
                #买单深度报价
                if (symbol in self._quote) and ('bids' in self._quote[symbol]) :
                    bid_order_price = 0
                    bid_order_volume = 0
                    bid_total_volume = 0
                    order_price = 0 
                    realtime_sell_after_order_limit_ratio = c.REALTIME_SELL_AFTER_ORDER_LIMIT_RATIO
                    i = 1
                    for bid in self._quote[symbol]['bids'] :
                        bid_order_price = math.floor(float(bid[0])*(10**init_precision[symbol]['price'])+0.1)/(10**init_precision[symbol]['price']) 
                        bid_order_volume = math.floor(float(bid[1])*(10**init_precision[symbol]['vol'])+0.1)/(10**init_precision[symbol]['vol'])
                        bid_total_volume += float(bid[1])
                        self.logger.debug('realtime-sell-_after_single_order-i,symbol,bidPrice,bidVolume,bidtotalVolume: %s,%s,%s,%s,%s' % (i, symbol, float(bid[0]), float(bid[1]), bid_total_volume))
                        #卖单-限制卖的太低价-卖单对手价追单滑点成本 = N档买单报价下单价格对比close价格比率小于等于负千五
                        #买单挂单前一档总交易量 = 卖单挂单当前档交易量-上一档交易量,卖单的舍去取整交易量为负
                        if (((bid_order_price/now_close-1) < realtime_sell_after_order_limit_ratio) and (i == 1)) or (((bid_order_price/now_close-1) < realtime_sell_after_order_limit_ratio) and (bid_total_volume < abs(volume))) and (_log_df.floor_change_volume.ix[symbol] < 0):
                            self.logger.info('-----------卖单挂单-实时追单--------------')
                            order_price = math.floor(now_close*(1+realtime_sell_after_order_limit_ratio)*(10**init_precision[symbol]['price'])+0.1)/(10**init_precision[symbol]['price']) 
                            self.logger.info('realtime-sell-_after_single_order-order_type, order_side, symbol, volume, order_pirce, now_close: %s,%s,%s,%s,%s,%s' % (order_type, order_side, symbol, abs(volume), order_price, now_close))
                            #实时追单
                            _open_orders = self._after_single_module(m_timestamp, 0, symbol,'') 
                            #type(_open_orders)是tuple类型,打印报错not all arguments converted during string format
                            self.logger.info('realtime-sell-_open_orders: %s' % (str(_open_orders)))
                            #if (not _open_orders is None) and len(_open_orders[0]) > 0 :
                            if symbol in symbol_list : 
                                _log_df.at[symbol,'position_realtime_order'] = 1 
                            break
                        i = i+1

            #买单实时追单-实时判断当成交价到close涨千5价格交易量小于成交量时，触发对手价追单,且只触发此币种1次实时追单
            if (self._order_status == 'buy_resting_order') and ('floor_change_volume' in _log_df) and (symbol in _log_df['floor_change_volume']) and (_log_df['floor_change_volume'][symbol] > 0) and ('now_close' in _log_df) and (symbol in _log_df['now_close']) and ('position_realtime_order' in _log_df) and (symbol in _log_df['position_realtime_order']) and (_log_df['position_realtime_order'][symbol] == 0) and (m_timestamp > self._realtime_buy_after_order_timestamp) :
                order_type = 'limit'
                order_side = 'buy'
                #理论调仓量按照系统要求保留位数舍去取整(正数舍去,负数的绝对值为进1取整)
                volume = _log_df['floor_change_volume'][symbol]
                #判断volume是否大于最小值
                if abs(volume) < float(init_precision[symbol]['min_vol']) :
                    volume = 0

                #close价格按照系统要求保留位数舍去取整
                now_close = math.floor(_log_df['now_close'][symbol]*(10**init_precision[symbol]['price'])+0.1)/(10**init_precision[symbol]['price'])
                #卖单深度报价
                if (symbol in self._quote) and ('asks' in self._quote[symbol]) :
                    ask_order_price = 0
                    ask_order_volume = 0
                    ask_total_volume = 0
                    order_price = 0 
                    realtime_buy_after_order_limit_ratio = c.REALTIME_BUY_AFTER_ORDER_LIMIT_RATIO 
                    i = 1
                    for ask in self._quote[symbol]['asks'] :
                        ask_order_price = math.floor(float(ask[0])*(10**init_precision[symbol]['price'])+0.1)/(10**init_precision[symbol]['price']) 
                        ask_order_volume = math.floor(float(ask[1])*(10**init_precision[symbol]['vol'])+0.1)/(10**init_precision[symbol]['vol'])
                        ask_total_volume += float(ask[1])
                        self.logger.debug('realtime-buy-_after_single_order-i,symbol,askPrice,askVolume,asktotalVolume: %s,%s,%s,%s,%s' % (i, symbol, float(ask[0]), float(ask[1]), ask_total_volume))
                        #买单-限制买的太高价-买单对手价追单滑点成本 = N档卖单报价下单价格对比close价格比率大于等于千五,买单的舍去取整交易量为正
                        if (((ask_order_price/now_close-1) > realtime_buy_after_order_limit_ratio) and (i == 1)) or (((ask_order_price/now_close-1) > realtime_buy_after_order_limit_ratio) and (ask_total_volume < abs(volume)))  and (_log_df.floor_change_volume.ix[symbol] > 0) : 
                            self.logger.info('-----------买单挂单-实时追单--------------')
                            order_price = math.floor(now_close*(1+realtime_buy_after_order_limit_ratio)*(10**init_precision[symbol]['price'])+0.1)/(10**init_precision[symbol]['price']) 
                            self.logger.info('realtime-buy_after_single_order-order_type, order_side, symbol, volume, order_pirce, now_close: %s,%s,%s,%s,%s,%s' % (order_type, order_side, symbol, abs(volume), order_price, now_close))
                            #实时追单
                            _open_orders = self._after_single_module(m_timestamp, 0, symbol, '') 
                            #type(_open_orders)是tuple类型,打印报错not all arguments converted during string format
                            self.logger.info('realtime-buy-_open_orders: %s' % (str(_open_orders)))
                            #if (not _open_orders is None) and len(_open_orders[0]) > 0 :
                            if symbol in symbol_list : 
                                _log_df.at[symbol,'position_realtime_order'] = 1 
                            break
                        i = i+1

        #公共-5档深度频道
        #返回参数
        #参数名	参数类型	描述
        #price	String	卖方深度
        #size	String	买方深度
        #timestamp	String	时间戳
        #num_orders	String	组成此条深度的订单数量
        #instrument_id	String	币对
        elif ('table' in message) and (message['table'] == 'spot/depth5') and ('data' in message):
            self.logger.debug("bids-asks: %s" %(message))

        #order-订单数据
        #参数名	类型	描述
        #order_id	String	订单ID
        #client_oid	String	由用户设置的订单ID
        #price	String	委托价格
        #size	String	委托数量（交易货币数量）
        #notional	String	买入金额，市价买入时返回
        #instrument_id	String	币对名称
        #side	String	buy or sell
        #type	String	limit,market(默认是limit)
        #timestamp	String	订单创建时间
        #filled_size	String	已成交数量
        #filled_notional	String	已成交金额
        #margin_trading	String	1 币币交易订单. 2 杠杆交易订单
        #order_type	String	0：普通委托 1：只做Maker（Post only） 2：全部成交或立即取消（FOK） 3：立即成交并取消剩余（IOC）
        #last_fill_px	String	最新成交价格 （如果没有，推0）
        #last_fill_qty	String	最新成交数量（如果没有，推0）
        #last_fill_time	String	最新成交时间（如果没有，推1970-01-01T00:00:00.000Z）
        #state	String	订单状态("-2":失败,"-1":撤单成功,"0":等待成交 ,"1":部分成交, "2":完全成交,"3":下单中,"4":撤单中,）
        #status为state旧版参数，会短期兼容，建议尽早切换state。
        #{'table': 'spot/order', 'data': [{'client_oid': '', 'filled_notional': '0', 'filled_size': '0', 'instrument_id': 'BTC-USDT', 'last_fill_px': '0', 'last_fill_qty': '0', 'last_fill_time': '1970-01-01T00:00:00.000Z', 'margin_trading': '1', 'notional': '', 'order_id': '2658394894578688', 'order_type': '0', 'price': '5132', 'side': 'buy', 'size': '0.00659918', 'status': 'open', 'timestamp': '2019-04-15T03:44:47.000Z', 'type': 'limit'}]}
        elif ('table' in message) and (message['table'] == 'spot/order') and ('data' in message):
            self.logger.debug("Order: %s",message)
            #0-等待成交-open, 2-完全成交(终态)-filled, 1-部分成交-part_filled, -1-已撤销(终态)-cancelled ,-2-订单失败-failure 
            for v in message['data'] :
                if (v) and ('instrument_id' in v) and ('order_id' in v) and ('status' in v) and ('timestamp' in v) and ('filled' in v['status']) and (self._order_status == 'sell_resting_order' or self._order_status == 'sell_after_order' or self._order_status == 'buy_resting_order') :
                    if (v['side'] == 'sell') :
                        #卖单实时挂单,通过已成交订单调整下单价格向后减少下单成本,通过下单未成交判断各币种是否进行位置调整
                        if ('realtime_open_nofilled_volume' in _log_df) and (v['instrument_id'] in _log_df['realtime_open_nofilled_volume']) and (abs(_log_df['realtime_open_nofilled_volume'][v['instrument_id']]) > float(init_precision[v['instrument_id']]['min_vol'])) :
                            self.logger.info('-----------1-3.卖单实时挂单-挂单位置调整-降低挂单成本向后调整--------------')
                            tmp_start_timestamp_1_3 = int(str(server_timestamp())[:10])
                            _m_timestamp = int(time.mktime(time.strptime(v['timestamp'][0:10]+" "+v['timestamp'][11:19], "%Y-%m-%d %H:%M:%S")))
                            tmp_realtime_sell_resting_order_timestamp_1_3 = copy.deepcopy(self._realtime_sell_resting_order_timestamp)
                            #固定检查实时卖挂单如果没执行先停下来
                            self._realtime_sell_resting_order_timestamp = c.MAX_TIMESTAMP 
                            _symbol_1_3 = v['instrument_id']
                            #取消当前卖单最小挂单价格订单
                            for key,value in self._order_realtime_price_volume[_symbol_1_3][min(self._order_realtime_price_volume[_symbol_1_3])].items():
                                _order_id_1_3 = key
                                try:
                                    #取消未成交订单
                                    #{"client_oid": "", "error_code": 0, "error_message": {}, "order_id": "2661455656587264", "result": true}
                                    #33027 撤单时已经撤销和撤销中的订单不能撤单
                                    #{"code":33027,"message":"Order has been revoked or revoked"}, 400
                                    _cancel_open_orders = {}
                                    spotAPI = spot.SpotAPI(apiKey, apiSecret, passphrase, True)
                                    _cancel_open_orders = spotAPI.revoke_order(_order_id_1_3,_symbol_1_3)

                                    #判断是成功取消未成交订单
                                    if (_cancel_open_orders) and ('result' in _cancel_open_orders) and (_cancel_open_orders['result'] == True) and ('order_id' in _cancel_open_orders) :
                                        self.logger.info('-----------1-3-1.取消挂单卖出未成交订单成功!: %s-%s' %(_symbol_1_3,_cancel_open_orders))
                                    else :
                                        self.logger.info('-----------1-3-1.取消挂单卖出未成交订单失败error!: %s-%s' %(_symbol_1_3,_cancel_open_orders))
                                except Exception as e:
                                    self.logger.error(traceback.format_exc())
                                    self.logger.error(e)

                            tmp_end_timestamp_1_3 = int(str(server_timestamp())[:10])
                            if (tmp_end_timestamp_1_3-tmp_start_timestamp_1_3 > 0) and (tmp_end_timestamp_1_3-tmp_start_timestamp_1_3 < c.REALTIME_SELL_RESTING_ORDER_INTERVAL_TIMESTAMP):
                                self._realtime_sell_resting_order_timestamp = int(self._order_timestamp)+tmp_end_timestamp_1_3-tmp_start_timestamp_1_3+c.REALTIME_SELL_RESTING_ORDER_INTERVAL_TIMESTAMP
                            else :
                                self._realtime_sell_resting_order_timestamp = int(self._order_timestamp)+c.REALTIME_SELL_RESTING_ORDER_INTERVAL_TIMESTAMP
                            self.logger.info('-----------1-3.卖单实时挂单-向后调整挂单位置-完成-%s,%s,%s,%s,%s,%s--------------' %(tmp_realtime_sell_resting_order_timestamp_1_3,tmp_end_timestamp_1_3,tmp_start_timestamp_1_3,self._realtime_sell_resting_order_timestamp,_m_timestamp,self._order_timestamp))
                        else :
                            self.logger.info('-----------1-3.卖单实时挂单-挂单位置调整-降低挂单成本向后调整-%s-不存在实时未成交' %(v['instrument_id']))

                        #买单实时挂单:如果固定实时买正在执行则先不执行,因为固定时间会后续继续下单 
                        #特别重要:如果不设定self._realtime_buy_resting_order_timestamp != 0会存在多次触发导致重复执行情况
                        if ('realtime_noopen_volume' in _log_df) and ((_log_df.realtime_noopen_volume[_log_df.realtime_noopen_volume>0].fillna(0).sum()) > 0.001) and (self._realtime_buy_resting_order_timestamp != 0):
                            self.logger.info('-----------3-0.买单实时挂单-卖出成功触发--------------')
                            tmp_realtime_buy_resting_order_timestamp_3_0 = copy.deepcopy(self._realtime_buy_resting_order_timestamp)
                            _m_timestamp = int(time.mktime(time.strptime(v['timestamp'][0:10]+" "+v['timestamp'][11:19], "%Y-%m-%d %H:%M:%S")))
                            #间隔N秒实时卖挂单1次
                            self._realtime_buy_resting_order_timestamp = 0
                            self.logger.info('-----------3-0.买单实时挂单-卖出成功触发-完成-%s,%s,%s--------------' %(tmp_realtime_buy_resting_order_timestamp_3_0,self._realtime_buy_resting_order_timestamp,_m_timestamp))
                        else :
                            self.logger.info('-----------3-0.买单实时挂单-卖出成功触发-%s-不存在实时未挂单或者当前已经触发买单实时挂单' %(v['instrument_id']))

                    if (v['side'] == 'buy') :
                        #买单实时挂单,通过下单未成交判断各币种是否进行位置调整
                        if ('realtime_open_nofilled_volume' in _log_df) and (v['instrument_id'] in _log_df['realtime_open_nofilled_volume']) and (abs(_log_df['realtime_open_nofilled_volume'][v['instrument_id']]) > float(init_precision[v['instrument_id']]['min_vol'])) :
                            self.logger.info('-----------3-3.买单实时挂单-挂单位置调整-降低挂单成本向后调整--------------')
                            tmp_start_timestamp_3_3 = int(str(server_timestamp())[:10])
                            _m_timestamp = int(time.mktime(time.strptime(v['timestamp'][0:10]+" "+v['timestamp'][11:19], "%Y-%m-%d %H:%M:%S")))
                            tmp_realtime_buy_resting_order_timestamp_3_3 = copy.deepcopy(self._realtime_buy_resting_order_timestamp)
                            self._realtime_buy_resting_order_timestamp = c.MAX_TIMESTAMP 
                            _symbol_3_3 = v['instrument_id']

                            #取消当前买单最大挂单价格订单
                            for key,value in self._order_realtime_price_volume[_symbol_3_3][max(self._order_realtime_price_volume[_symbol_3_3])].items():
                                _order_id_3_3 = key
                                try:
                                    #取消未成交订单
                                    #{"client_oid": "", "error_code": 0, "error_message": {}, "order_id": "2661455656587264", "result": true}
                                    #33027 撤单时已经撤销和撤销中的订单不能撤单
                                    #{"code":33027,"message":"Order has been revoked or revoked"}, 400
                                    _cancel_open_orders = {}
                                    spotAPI = spot.SpotAPI(apiKey, apiSecret, passphrase, True)
                                    _cancel_open_orders = spotAPI.revoke_order(_order_id_3_3,_symbol_3_3)

                                    #判断是成功取消未成交订单
                                    if (_cancel_open_orders) and ('result' in _cancel_open_orders) and (_cancel_open_orders['result'] == True) and ('order_id' in _cancel_open_orders) :
                                        self.logger.info('-----------3-3-1.取消挂单买入未成交订单成功!: %s-%s' %(_symbol_3_3,_cancel_open_orders))
                                    else :
                                        self.logger.info('-----------3-3-1.取消挂单买入未成交订单失败error!: %s-%s' %(_symbol_3_3,_cancel_open_orders))
                                except Exception as e:
                                    self.logger.error(traceback.format_exc())
                                    self.logger.error(e)

                            tmp_end_timestamp_3_3 = int(str(server_timestamp())[:10])
                            if (tmp_end_timestamp_3_3-tmp_start_timestamp_3_3 > 0) and (tmp_end_timestamp_3_3-tmp_start_timestamp_3_3 < c.REALTIME_BUY_RESTING_ORDER_INTERVAL_TIMESTAMP):
                                self._realtime_buy_resting_order_timestamp = int(self._order_timestamp)+tmp_end_timestamp_3_3-tmp_start_timestamp_3_3+c.REALTIME_BUY_RESTING_ORDER_INTERVAL_TIMESTAMP
                            else :
                                self._realtime_buy_resting_order_timestamp = int(self._order_timestamp)+c.REALTIME_BUY_RESTING_ORDER_INTERVAL_TIMESTAMP
                            self.logger.info('-----------3-3.买单实时挂单-挂单位置调整-完成-%s,%s,%s,%s,%s,%s--------------' %(tmp_realtime_buy_resting_order_timestamp_3_3,tmp_end_timestamp_3_3,tmp_start_timestamp_3_3,self._realtime_buy_resting_order_timestamp,_m_timestamp,self._order_timestamp))
                        else :
                            self.logger.info('-----------3-3.买单实时挂单-挂单位置调整-降低挂单成本向后调整-%s-不存在实时未成交' %(v['instrument_id']))

        #Position-order.match-持仓数据
        #{'table': 'spot/account', 'data': [{'balance': '136.781211684', 'available': '102.914219924', 'currency': 'USDT', 'id': '9196334', 'hold': '33.86699176'}]}
        #{'table': 'spot/account', 'data': [{'balance': '183.770262803', 'available': '183.770262803', 'currency': 'USDT', 'id': '9196334', 'hold': '0'}]}
        #{'table': 'spot/account', 'data': [{'balance': '0.00013148474', 'available': '0.00013148474', 'currency': 'BTC', 'id': '9196334', 'hold': '0'}]}
        #参数名	类型	描述
        #currency	String	币种
        #balance	String	余额
        #hold	String	冻结(不可用)
        #available	String	可用于交易或资金划转的数量
        #id	String	账户 id
        elif ('table' in message) and (message['table'] == 'spot/account') and ('data' in message):
            self.logger.debug("Position: %s" %(message))

    #实时挂单模块
    def _realtime_resting_single_module(self, m_timestamp, symbol, order_side) :
        #1.实时卖单挂单
        if (order_side == 'sell') :
            self.logger.debug('卖单挂单')
            #模型输出的取整后的调仓交易量进行调仓
            if ('realtime_noopen_volume' in _log_df) and (len(_log_df['realtime_noopen_volume']) > 0) :
                j = 0 
                for i in list(range(len(_log_df['realtime_noopen_volume']))) : 
                    _symbol = _log_df['realtime_noopen_volume'].index[i]
                    #不等于报价货币的交易币种,或者symbol为''或者symbol需要挂单币种
                    if (_symbol != quote_currency) and ((symbol == '') or (symbol == _symbol)) and ('output_change_volume' in _log_df) and (_symbol in _log_df['output_change_volume']) and (_log_df['output_change_volume'][_symbol] < 0):
                        _volume = math.floor(_log_df['realtime_noopen_volume'][i]*(10**init_precision[_symbol]['vol'])+0.1)/(10**init_precision[_symbol]['vol'])
                        #判断volume是否大于最小值
                        if abs(_volume) < float(init_precision[_symbol]['min_vol']) :
                            _volume = 0

                        #判断未挂单量是否大于总挂单量乘以比率系数,默认为100%
                        if abs(_volume) <= abs(math.floor(_log_df['floor_change_volume'][_symbol]*c.SELL_RESTING_ORDER_LIMIT_VOLUME_RATIO*(10**init_precision[_symbol]['vol'])+0.1)/(10**init_precision[_symbol]['vol'])) :
                            _now_volume = _volume
                        else :
                            _now_volume = math.floor(_log_df['floor_change_volume'][_symbol]*c.SELL_RESTING_ORDER_LIMIT_VOLUME_RATIO*(10**init_precision[_symbol]['vol'])+0.1)/(10**init_precision[_symbol]['vol']) 

                        #判断_now_volume是否大于最小值
                        if abs(_now_volume) < float(init_precision[_symbol]['min_vol']) :
                            _now_volume = 0

                        #close价格按照系统要求保留位数舍去取整
                        _now_close = math.floor(_log_df['now_close'][i]*(10**init_precision[_symbol]['price'])+0.1)/(10**init_precision[_symbol]['price'])
                        #判断卖出挂单以未取整和判断最小值之前的原始数据判断,卖出挂单-模型输出交易量为负小于0
                        if _log_df['output_change_volume'][i] < 0 :
                            _order_type = 'limit'
                            _order_side = 'sell'
                            #卖挂单-判断取整后小于0交易量
                            if _now_volume < 0 :
                                #挂单价格成交
                                self._resting_single(m_timestamp, _symbol, _now_volume, _now_close, _order_side, _order_type, '')
                                j = j+1
            else :
                self.logger.info('未获取到模型输出的调仓信息:%s' %(_log_df.T))

        elif (order_side == 'buy') :
            self.logger.debug('--->买单实时挂单处理<---')
            #1.确定当前可用usdt
            self.logger.debug('1.确定当前可用usdt')
            spotAPI = spot.SpotAPI(apiKey, apiSecret, passphrase, True)
            balance_result = spotAPI.get_account_info()
            if balance_result :
                for val in balance_result :
                    if val['currency'] == quote_currency :
                        #available 可用于交易数量
                        quote_currency_balance = float(val['available'])

                tmp_quote_currency_balance = 0
                if quote_currency in self._position_detail :
                    tmp_quote_currency_balance = float(self._position_detail[quote_currency]['available'])

                if quote_currency_balance == tmp_quote_currency_balance :
                    logger.info('获取当前账户资产成功!quote_currency_balance,tmp_quote_currency_balance: %s,%s' %(quote_currency_balance,tmp_quote_currency_balance))
                else :
                    logger.info('获取当前账户资产成功,但存在实时接收数据比对差异,使用查询结果!quote_currency_balance,tmp_quote_currency_balance: %s,%s' %(quote_currency_balance,tmp_quote_currency_balance))
            else :
                #参数名	类型	描述
                #currency	String	币种
                #balance	String	余额
                #hold	String	冻结(不可用)
                #available	String	可用于交易或资金划转的数量
                #id	String	账户 id
                if quote_currency in self._position_detail :
                    quote_currency_balance = float(self._position_detail[quote_currency]['available'])
                logger.info('获取当前账户资产失败,使用实时接收数据!tmp_quote_currency_balance %s,%s' % (balance_result,quote_currency_balance))

            #获取到模型实时未下单信息
            if ('realtime_noopen_volume' in _log_df) and (len(_log_df['realtime_noopen_volume']) > 0) :
                j = 0 
                for i in list(range(len(_log_df['realtime_noopen_volume']))) : 
                    _symbol = _log_df['realtime_noopen_volume'].index[i]

                    #不等于报价货币的交易币种,或者symbol为''或者symbol需要挂单币种
                    if (_symbol != quote_currency) and ((symbol == '') or (symbol == _symbol)) and ('output_change_volume' in _log_df) and (_symbol in _log_df['output_change_volume']) and (_log_df['output_change_volume'][_symbol] > 0)  :
                        #close价格按照系统要求保留位数舍去取整
                        _now_close = math.floor(_log_df['now_close'][_symbol]*(10**init_precision[_symbol]['price'])+0.1)/(10**init_precision[_symbol]['price'])
                        #理论调仓量按照系统要求保留位数舍去取整(正数舍去,负数的绝对值为进1取整)
                        tmp_realtime_noopen_volume = math.floor(_log_df['realtime_noopen_volume'][_symbol]*(10**init_precision[_symbol]['vol'])+0.1)/(10**init_precision[_symbol]['vol'])
                        
                        #根据usdt量和各币种购买金额比率计算=usdt量*此币种购买usdt金额比率/当前close价格
                        _volume = math.floor((quote_currency_balance*_log_df['output_change_ratio'][i]/_log_df['now_close'][i])*(10**init_precision[_symbol]['vol'])+0.1)/(10**init_precision[_symbol]['vol'])
                        
                        logger.info('当前usdt持仓可以购买量和未下单量_symbol, _volume, tmp_realtime_noopen_volume-%s,%s,%s' %(_symbol, _volume, tmp_realtime_noopen_volume))
                        if (_volume+float(init_precision[_symbol]['min_vol'])) >= tmp_realtime_noopen_volume:
                            _now_volume = tmp_realtime_noopen_volume
                        #解决极小值无法按比例分配,如果当前可分频下单量+最小下单量小于未下单,且当前可分频下单量小于最小下单量,则按照当前可分配下单量+最小下单量下单
                        elif _volume < float(init_precision[_symbol]['min_vol']): 
                            _now_volume = _volume+float(init_precision[_symbol]['min_vol'])
                        else :
                            _now_volume = _volume

                        #判断_now_volume是否大于最小值
                        if abs(_now_volume) < float(init_precision[_symbol]['min_vol']) :
                            _now_volume = 0

                        if _log_df['output_change_volume'][i] > 0 :
                            _order_type = 'limit'
                            _order_side = 'buy'
                            #买挂单-判断取整后小于0交易量
                            if _now_volume > 0 :
                                #挂单价格成交
                                self._resting_single(m_timestamp, _symbol, _now_volume, _now_close, _order_side, _order_type, '')
                                j = j+1
            else :
                self.logger.info('3-2.未获取到模型输出的调仓信息:%s' %(_log_df.T))

    #挂单模块:1.卖单挂单-sell_resting_order,2.买单挂单buy_resting_order,根据模型输出的各币种交易量进行挂单
    def _resting_single_module(self, m_timestamp, symbol, order_side) :
        #1.卖单挂单-sell_resting_order
        if (order_side == 'sell') :
            self.logger.debug('卖单挂单')
            #模型输出的取整后的调仓交易量进行调仓
            if ('floor_change_volume' in _log_df) and (len(_log_df['floor_change_volume']) > 0) :
                j = 0 
                for i in list(range(len(_log_df['floor_change_volume']))) : 
                    _symbol = _log_df['floor_change_volume'].index[i]
                    #不等于报价货币的交易币种,或者symbol为''或者symbol需要挂单币种
                    if (_symbol != quote_currency) and ((symbol == '') or (symbol == _symbol)) :
                        _volume = _log_df['floor_change_volume'][_symbol]
                        #判断volume是否大于最小值
                        if abs(_volume) < float(init_precision[_symbol]['min_vol']) :
                            _volume = 0

                        #每次挂单占总交易量的比率,默认为100%
                        _now_volume = _volume*c.SELL_RESTING_ORDER_LIMIT_VOLUME_RATIO

                        #判断_now_volume是否大于最小值
                        if abs(_now_volume) < float(init_precision[_symbol]['min_vol']) :
                            _now_volume = 0

                        #close价格按照系统要求保留位数舍去取整
                        _now_close = math.floor(_log_df['now_close'][_symbol]*(10**init_precision[_symbol]['price'])+0.1)/(10**init_precision[_symbol]['price'])
                        #判断卖出挂单以未取整和判断最小值之前的原始数据判断,卖出挂单-模型输出交易量为负小于0
                        if _log_df['output_change_volume'][i] < 0 :
                            _order_type = 'limit'
                            _order_side = 'sell'
                            #调仓方向:空无方向默认向前,front向前调仓,back向后调仓
                            _direction = ''
                            #卖挂单-判断取整后小于0交易量
                            if _now_volume < 0 :
                                #挂单价格成交
                                self._resting_single(m_timestamp, _symbol, _now_volume, _now_close, _order_side, _order_type, _direction)
                                j = j+1
                            #卖挂单-判断取整后等于0交易量
                            elif _now_volume == 0 :
                                order_result = {'client_oid': '', 'error_code': 'volume-0', 'error_message': 'sell-volume-0', 'order_id': '', 'result': 'error'} 
                                #解析订单结果
                                self._orderResult(order_result, m_timestamp, _now_volume, _symbol, _order_type, _order_side, _now_close)

                #如果卖单没有符合挂单价格则修改买单挂单时间为当前时间,进行立即买挂单,且挂单比率为1
                if (j == 0) and (c.SELL_RESTING_ORDER_LIMIT_VOLUME_RATIO == 1) :
                    self.logger.info('卖单没有需要挂单的币种,提前进入卖单追单阶段!')
                    self._sell_after_order_timestamp = m_timestamp
                    #self.logger.info('卖单完成提前进入买单阶段')
                    #self._buy_resting_order_timestamp = m_timestamp 
                    #关闭实时卖挂单
                    self._realtime_sell_resting_order_timestamp = c.MAX_TIMESTAMP 
            else :
                self.logger.info('未获取到模型输出的调仓信息:%s' %(_log_df.T))
        elif (order_side == 'buy') :
            self.logger.debug('买单挂单')
            #获取到模型输出的调仓信息
            if ('floor_change_volume' in _log_df) and (len(_log_df['floor_change_volume']) > 0) :
                for i in list(range(len(_log_df['floor_change_volume']))) : 
                    _symbol = _log_df['floor_change_volume'].index[i]
                    #不等于报价货币的交易币种,或者symbol为''或者symbol需要挂单币种
                    if (_symbol != quote_currency) and ((symbol == '') or (symbol == _symbol)) :
                        _volume = _log_df['floor_change_volume'][_symbol]
                        #判断volume是否大于最小值
                        if abs(_volume) < float(init_precision[_symbol]['min_vol']) :
                            _volume = 0

                        #每次挂单占总交易量的比率，默认为100%
                        _now_volume = _volume*c.BUY_RESTING_ORDER_LIMIT_VOLUME_RATIO

                        #判断_now_volume是否大于最小值
                        if abs(_now_volume) < float(init_precision[_symbol]['min_vol']) :
                            _now_volume = 0

                        #close价格按照系统要求保留位数舍去取整
                        _now_close = math.floor(_log_df['now_close'][_symbol]*(10**init_precision[_symbol]['price'])+0.1)/(10**init_precision[_symbol]['price'])
                        #模型输出交易量买入挂单为正大于等于0
                        if _log_df['output_change_volume'][i] >= 0 :
                            _order_type = 'limit'
                            _order_side = 'buy'
                            #调仓方向:空无方向默认向前,front向前调仓,back向后调仓
                            _direction = ''
                            #买挂单-判断取整后大于0交易量
                            if _now_volume > 0 :
                                #挂单价格成交
                                self._resting_single(m_timestamp, _symbol, _now_volume, _now_close, _order_side, _order_type, _direction)
                            #买挂单-判断取整前后等于0交易量
                            elif _now_volume == 0 :
                                order_result = {'client_oid': '', 'error_code': 'volume-0', 'error_message': 'buy-volume-0', 'order_id': '', 'result': 'error'} 
                                #解析订单结果
                                self._orderResult(order_result, m_timestamp, _now_volume, _symbol, _order_type, _order_side, _now_close)
            else :
                self.logger.info('未获取到模型输出的调仓信息:%s' %(_log_df.T))

        else :
            self.logger.info('挂单异常')

    #实时挂单模块:单一币种处理,驱动方式间隔多少秒检查一次;bid1和ask1价格变动多少进行调节;
    def _realtime_resting_single_position_module(self, m_timestamp, symbol, order_side, direction) :
        asks_list = [] 
        #使用全量深度卖挂单报价:如果存在增量深度挂单按照10档挂单,否则存在5档全量挂单按照5档挂单,否则按照1档挂单
        if (symbol in self._quote) and ('asks' in self._quote[symbol]) and (len(self._quote[symbol]['asks']) >= 10) :
            self.logger.info('_resting_single-leng(asks): %s,%s' % (symbol,len(self._quote[symbol]['asks'])))
            asks_list = self._quote[symbol]['asks']
        #使用5档深度卖挂单报价:全量深度卖挂单报价小于5个
        elif (symbol in self._quote5) and ('asks' in self._quote5[symbol]) and (len(self._quote5[symbol]['asks']) == 5):
            self.logger.info('asks quote+quote5: %s,%s,%s' % (symbol,self._quote[symbol]['asks'],self._quote5[symbol]['asks']))
            asks_list = self._quote5[symbol]['asks']

        bids_list = [] 
        if (symbol in self._quote) and ('bids' in self._quote[symbol]) and (len(self._quote[symbol]['bids']) >= 10) :
            bids_list = self._quote[symbol]['bids']
        #使用5档深度卖挂单报价:全量深度卖挂单报价小于5个
        elif (symbol in self._quote5) and ('bids' in self._quote5[symbol]) and (len(self._quote5[symbol]['bids']) == 5):
            bids_list = self._quote5[symbol]['bids']

        #1.卖单实时挂单-sell_resting_order
        if (order_side == 'sell') :
            self.logger.debug('--->卖单实时挂单处理<---')

            #判断存在实时未成交的价格和量
            #self._order_realtime_price_volume {'ETH-USDT': {}, 'EOS-USDT': {}, 'BCH-USDT': {}, 'BTC-USDT': {}, 'XRP-USDT': {0.319: {3289753288778752: 4001.893}}}
            if (asks_list) and (bids_list) and (symbol in self._order_realtime_price_volume) and (self._order_realtime_price_volume[symbol]) and (symbol in self._trade_tmp) and ('close' in self._trade_tmp[symbol]) :
                self.logger.info('-----------1-2.卖单挂单信息-symbol, asks_list[0],min(self._order_realtime_price_volume[symbol]),self._trade_tmp[symbol][close],bids_list[0]-%s,%s,%s,%s,%s' %(symbol, asks_list[0],min(self._order_realtime_price_volume[symbol]),self._trade_tmp[symbol]['close'],bids_list[0]))
            elif (asks_list) and (bids_list) and (symbol in self._order_realtime_price_volume) and (self._order_realtime_price_volume[symbol]):
                self.logger.info('-----------1-2.卖单挂单信息-symbol, asks_list[0],min(self._order_realtime_price_volume[symbol]),bids_list[0]-%s,%s,%s,%s' %(symbol, asks_list[0],min(self._order_realtime_price_volume[symbol]),bids_list[0]))

            #卖单取askn档价格判断是否小于当前下单最小价格，如果小于则重新调整挂单位置
            if (asks_list) and (symbol in self._order_realtime_price_volume) and (self._order_realtime_price_volume[symbol]) and (float(asks_list[c.SELL_RESTING_ORDER_LIMIT_POSITION_FRONT][0]) > 0) and (float(asks_list[c.SELL_RESTING_ORDER_LIMIT_POSITION_FRONT][0]) < min(self._order_realtime_price_volume[symbol])) :
                self.logger.info('-----------1-2.卖单取askn档价格判断是否小于当前下单最小价格，如果小于则重新调整挂单位置')
                #卖n档价格/close价格大于等于负千5,执行挂单位置调整，如果小于负千5保持不动
                if ('now_close' in _log_df) and (symbol in _log_df['now_close']) and (float(asks_list[0][0])/_log_df['now_close'][symbol]-1 >= c.SELL_RESTING_ORDER_LIMIT_RATIO_MAX):

                    _open_orders = []
                    _open_orders_n = 1
                    for symbol_o in symbol_list :
                        if (symbol_o != quote_currency) : 
                            #获取未成交订单
                            spotAPI = spot.SpotAPI(apiKey, apiSecret, passphrase, True)
                            _open_orders_s = spotAPI.get_orders_pending('','','',symbol_o)
                            if _open_orders_n == 1:
                                if (_open_orders_s) :
                                    _open_orders = _open_orders_s[0]
                            else :
                                if (_open_orders_s) :
                                    _open_orders = _open_orders + _open_orders_s[0]
                            _open_orders_n += 1
                    _open_orders = [_open_orders]

                    #获取未成交订单
                    #spotAPI = spot.SpotAPI(apiKey, apiSecret, passphrase, True)
                    #_open_orders = spotAPI.get_orders_pending('','','','')

                    self.logger.info('-----------1-2-1.查询挂单卖出未成交订单: %s,%s,%s' %(symbol, order_side, _open_orders))
                    if (_open_orders) and len(_open_orders[0]) > 0 :
                        tmp_nofilled_volume = {}
                        revoke_order_params_list = []
                        #revoke_order_params_list = [{'instrument_id': 'BTC-USDT', 'order_ids':[3451042910179328, 3451042910179329]}]
                        tmp_revoke_order_params = {} 
                        for val in _open_orders[0] :
                            _symbol = val['instrument_id']
                            _order_side = val['side']
                            #卖单为负值,临时未成交交易量 = 成交量-下单量
                            tmp_no_deal_volume = math.floor((float(val['filled_size'])-float(val['size']))*(10**init_precision[_symbol]['vol'])+0.1)/(10**init_precision[_symbol]['vol'])

                            #symbol=_symbol存在卖未成交订单
                            if (symbol == _symbol) and (order_side == _order_side):
                                #未成交订单交易量要大于等于最小交易量
                                if (abs(tmp_no_deal_volume) >= float(init_precision[_symbol]['min_vol'])) : 
                                    _order_id = int(val['order_id'])
                                    if tmp_revoke_order_params :
                                        tmp_revoke_order_params['order_ids'].append(_order_id)
                                    else :
                                        tmp_revoke_order_params = {'instrument_id': symbol, 'order_ids':[_order_id]}

                                    if len(tmp_revoke_order_params['order_ids']) == 10 :
                                        revoke_order_params_list.append(tmp_revoke_order_params)
                                        tmp_revoke_order_params = {}
                                else :
                                    self.logger.info('-----------1-2-2-1.未成交订单未交易量小于最小交易量-不进行取消: %s-%s' %(tmp_no_deal_volume,val))
                        if (tmp_revoke_order_params) and (len(tmp_revoke_order_params['order_ids']) > 0) : 
                            revoke_order_params_list.append(tmp_revoke_order_params)

                        if revoke_order_params_list :
                            for revoke_order_params in revoke_order_params_list :
                                _cancel_open_orders_list = {}
                                try:
                                    #取消未成交订单
                                    #{"client_oid": "", "error_code": 0, "error_message": {}, "order_id": "2661455656587264", "result": true}
                                    #33027 撤单时已经撤销和撤销中的订单不能撤单
                                    #{"code":33027,"message":"Order has been revoked or revoked"}, 400
                                    self.logger.info('symbol,revoke_order_params : %s,%s' %(_symbol,revoke_order_params))
                                    if (revoke_order_params) and (len(revoke_order_params['order_ids']) > 0) and (len(revoke_order_params['order_ids']) <= 10) :
                                        spotAPI = spot.SpotAPI(apiKey, apiSecret, passphrase, True)
                                        #_cancel_open_orders = spotAPI.revoke_order(_order_id,_symbol)
                                        _cancel_open_orders_list = spotAPI.revoke_orders([revoke_order_params])
                                        #{'btc-usdt': [{'client_oid': 'id15671593641', 'order_id': '3451042910179328', 'result': True}, {'client_oid': 'id15671593642', 'order_id': '3451042910179329', 'result': True}]}
                                        self.logger.info('-----------1-2-2.批量取消挂单卖出未成交订单: %s-%s' %(_symbol,_cancel_open_orders_list))
                                except Exception as e:
                                    self.logger.error(traceback.format_exc())
                                    self.logger.error(e)

                                if (_cancel_open_orders_list) :
                                    for symbol_l in _cancel_open_orders_list:
                                        for _cancel_open_orders in _cancel_open_orders_list[symbol_l] :
                                            _order_id = _cancel_open_orders['order_id'] 

                                            #判断是成功取消未成交订单
                                            if (_cancel_open_orders) and ('result' in _cancel_open_orders) and (_cancel_open_orders['result'] == True) and ('order_id' in _cancel_open_orders) :
                                                self.logger.info('-----------1-2-2-1.取消挂单卖出未成交订单成功!: %s-%s' %(symbol_l.upper(),_cancel_open_orders))

                                                #查询指定订单详情获取未成交数量
                                                #{"client_oid": "", "created_at": "2019-04-15T16:43:10.000Z", "filled_notional": "0", "filled_size": "0", "funds": "", "instrument_id": "BTC-USDT", "notional": "", "order_id": "2661455656587264", "order_type": "0", "price": "5120", "product_id": "BTC-USDT", "side": "buy", "size": "0.01", "status": "cancelled", "timestamp": "2019-04-15T16:43:10.000Z", "type": "limit"}
                                                spotAPI = spot.SpotAPI(apiKey, apiSecret, passphrase, True)
                                                order_info_result = spotAPI.get_order_info(symbol_l.upper(), _order_id)
                                                self.logger.info('获取未成交订单信息: %s-%s' %(_order_id,order_info_result))
                                                if (order_info_result) and ('status' in order_info_result) and (order_info_result['status'] != 'filled') :
                                                    if (symbol_l.upper() in tmp_nofilled_volume) :
                                                        tmp_nofilled_volume[symbol_l.upper()] += math.floor((float(order_info_result['filled_size'])-float(order_info_result['size']))*(10**init_precision[symbol_l.upper()]['vol'])+0.1)/(10**init_precision[symbol_l.upper()]['vol'])
                                                    else :
                                                        tmp_nofilled_volume[symbol_l.upper()] = math.floor((float(order_info_result['filled_size'])-float(order_info_result['size']))*(10**init_precision[symbol_l.upper()]['vol'])+0.1)/(10**init_precision[symbol_l.upper()]['vol']) 
                                            else :
                                                self.logger.info('-----------1-2-2-2.取消挂单卖出未成交订单失败error!: %s-%s' %(symbol_l.upper(),_cancel_open_orders))
                        self.logger.info('获取取消订单统计未成交数据: %s' %(tmp_nofilled_volume))
                        self.logger.info('-----------1-2-3.根据当前未成交情况进行卖单挂单')
                        #获取到模型实时取消订单后未未下单信息
                        if ('realtime_noopen_volume' in _log_df) and (len(_log_df['realtime_noopen_volume']) > 0) :
                            for i in list(range(len(_log_df['realtime_noopen_volume']))) : 
                                _symbol = _log_df['realtime_noopen_volume'].index[i]

                                #不等于报价货币的交易币种,或者symbol为''或者symbol需要挂单币种,判断未成交信息不为空
                                if (_symbol != quote_currency) and (symbol == _symbol) and (_symbol in tmp_nofilled_volume) and (tmp_nofilled_volume[_symbol]) and (_symbol in _log_df['realtime_noopen_volume']):

                                    #判断回报的到信息与取消订单统计是否一致,如果不一致按照取消订单统计,有可能回报未下单会大于统计未下单,因为还有其它未下单
                                    if (_log_df['realtime_noopen_volume'][_symbol] != tmp_nofilled_volume[_symbol]) :
                                        self.logger.info('判断回报的取消订单后的未下单信息与取消订单统计是否一致,如果不一致按照取消订单统计_log_df[realtime_noopen_volume][_symbol],tmp_nofilled_volume[_symbol]-%s,%s' %(_log_df['realtime_noopen_volume'][_symbol],tmp_nofilled_volume[_symbol]))

                                    #理论调仓量按照系统要求保留位数舍去取整(正数舍去,负数的绝对值为进1取整)
                                    _now_volume = math.floor(tmp_nofilled_volume[_symbol]*(10**init_precision[_symbol]['vol'])+0.1)/(10**init_precision[_symbol]['vol'])

                                    #判断_now_volume是否大于最小值
                                    if abs(_now_volume) < float(init_precision[_symbol]['min_vol']) :
                                        _now_volume = 0

                                    #close价格按照系统要求保留位数舍去取整
                                    _now_close = math.floor(_log_df['now_close'][_symbol]*(10**init_precision[_symbol]['price'])+0.1)/(10**init_precision[_symbol]['price'])
                                    #卖出挂单-模型输出交易量为负小于0
                                    if _log_df['output_change_volume'][_symbol] < 0 :
                                        _order_type = 'limit'
                                        _order_side = 'sell'
                                        #卖挂单-判断取整后小于0交易量
                                        if _now_volume < 0 :
                                            #挂单价格成交
                                            self._resting_single(m_timestamp, _symbol, _now_volume, _now_close, _order_side, _order_type, direction)
                else:
                    self.logger.info('-----------1-2.卖n档价格/close价格小于负千5,不进行挂单位置调整')
            else :
                self.logger.info('-----------1-2.卖单取askn档价格判断是否大于等于当前下单最小价格，不调整挂单位置')

        #确定当前usdt金额进行多币种均匀买挂单
        elif (order_side == 'buy') :
            self.logger.debug('--->买单实时挂单处理<---')

            #判断存在实时未成交的价格和量
            #self._order_realtime_price_volume {'ETH-USDT': {}, 'EOS-USDT': {}, 'BCH-USDT': {}, 'BTC-USDT': {}, 'XRP-USDT': {0.319: {3289753288778752: 4001.893}}}
            if (asks_list) and (bids_list) and (symbol in self._order_realtime_price_volume) and (self._order_realtime_price_volume[symbol]) and (symbol in self._trade_tmp) and ('close' in self._trade_tmp[symbol]) :
                self.logger.info('-----------3-2.买单挂单信息-symbol, asks_list[0],max(self._order_realtime_price_volume[symbol]),self._trade_tmp[symbol][close],bids_list[0]-%s,%s,%s,%s,%s' %(symbol, asks_list[0],max(self._order_realtime_price_volume[symbol]),self._trade_tmp[symbol]['close'],bids_list[0]))
            elif (asks_list) and (bids_list) and (symbol in self._order_realtime_price_volume) and (self._order_realtime_price_volume[symbol]) :
                self.logger.info('-----------3-2.买单挂单信息-symbol, asks_list[0],max(self._order_realtime_price_volume[symbol]),bids_list[0]-%s,%s,%s,%s' %(symbol, asks_list[0],max(self._order_realtime_price_volume[symbol]),bids_list[0]))

            #买单取bidn档价格判断是否大于当前下单最大价格，如果大于则重新调整挂单位置
            if (bids_list) and (symbol in self._order_realtime_price_volume) and (self._order_realtime_price_volume[symbol]) and (float(bids_list[c.SELL_RESTING_ORDER_LIMIT_POSITION_FRONT][0]) > 0) and (float(bids_list[c.SELL_RESTING_ORDER_LIMIT_POSITION_FRONT][0]) > max(self._order_realtime_price_volume[symbol])) :
                self.logger.info('-----------3-2.买单取bidn档价格判断是否大于当前下单最大价格，如果大于则重新调整挂单位置')
                #买n档价格/close价格小于等于千5,执行挂单位置调整，如果大于千5保持不动
                if ('now_close' in _log_df) and (symbol in _log_df['now_close']) and (float(bids_list[0][0])/_log_df['now_close'][symbol]-1 >= c.SELL_RESTING_ORDER_LIMIT_RATIO_MAX):

                    _open_orders = []
                    _open_orders_n = 1
                    for symbol_o in symbol_list :
                        if (symbol_o != quote_currency) : 
                            #获取未成交订单
                            spotAPI = spot.SpotAPI(apiKey, apiSecret, passphrase, True)
                            _open_orders_s = spotAPI.get_orders_pending('','','',symbol_o)
                            if _open_orders_n == 1:
                                if (_open_orders_s) :
                                    _open_orders = _open_orders_s[0]
                            else :
                                if (_open_orders_s) :
                                    _open_orders = _open_orders + _open_orders_s[0]
                            _open_orders_n += 1
                    _open_orders = [_open_orders]

                    #获取未成交订单
                    #spotAPI = spot.SpotAPI(apiKey, apiSecret, passphrase, True)
                    #_open_orders = spotAPI.get_orders_pending('','','','')

                    self.logger.info('1.查询对手价格挂单买入未成交订单: %s,%s,%s' %(symbol, order_side, _open_orders))
                    if (_open_orders) and len(_open_orders[0]) > 0 :
                        tmp_nofilled_volume = {}
                        revoke_order_params_list = []
                        tmp_revoke_order_params = {} 
                        for val in _open_orders[0] :
                            _symbol = val['instrument_id']
                            #临时未成交交易量 = 下单量-成交量
                            tmp_no_deal_volume = math.floor((float(val['size'])-float(val['filled_size']))*(10**init_precision[_symbol]['vol'])+0.1)/(10**init_precision[_symbol]['vol'])

                            #symbol为''或者symbol存在未成交订单
                            if (((symbol == '') or (symbol == _symbol))) and ((order_side == '') or (order_side == val['side'])):
                                #未成交订单交易量要大于等于最小交易量
                                if (abs(tmp_no_deal_volume) >= float(init_precision[_symbol]['min_vol'])) : 
                                    _order_id = int(val['order_id'])
                                    if tmp_revoke_order_params :
                                        tmp_revoke_order_params['order_ids'].append(_order_id)
                                    else :
                                        tmp_revoke_order_params = {'instrument_id': symbol, 'order_ids':[_order_id]}

                                    if len(tmp_revoke_order_params['order_ids']) == 10 :
                                        revoke_order_params_list.append(tmp_revoke_order_params)
                                        tmp_revoke_order_params = {}
                                else :
                                    self.logger.info('2-3.未成交订单未交易量小于最小交易量-不进行取消: %s-%s' %(tmp_no_deal_volume,val))

                        if (tmp_revoke_order_params) and (len(tmp_revoke_order_params['order_ids']) > 0) : 
                            revoke_order_params_list.append(tmp_revoke_order_params)

                        if revoke_order_params_list :
                            for revoke_order_params in revoke_order_params_list :
                                _cancel_open_orders_list = {}
                                try:
                                    #取消未成交订单
                                    #{"client_oid": "", "error_code": 0, "error_message": {}, "order_id": "2661455656587264", "result": true}
                                    #33027 撤单时已经撤销和撤销中的订单不能撤单
                                    #{"code":33027,"message":"Order has been revoked or revoked"}, 400
                                    self.logger.info('symbol,revoke_order_params : %s,%s' %(_symbol,revoke_order_params))
                                    if (revoke_order_params) and (len(revoke_order_params['order_ids']) > 0) and (len(revoke_order_params['order_ids']) <= 10) :
                                        #_cancel_open_orders = {}
                                        spotAPI = spot.SpotAPI(apiKey, apiSecret, passphrase, True)
                                        #_cancel_open_orders = spotAPI.revoke_order(_order_id,_symbol)
                                        _cancel_open_orders_list = spotAPI.revoke_orders([revoke_order_params])
                                        #{'btc-usdt': [{'client_oid': 'id15671593641', 'order_id': '3451042910179328', 'result': True}, {'client_oid': 'id15671593642', 'order_id': '3451042910179329', 'result': True}]}
                                        self.logger.info('-----------2.批量取消挂单买入未成交订单: %s-%s' %(_symbol,_cancel_open_orders_list))
                                except Exception as e:
                                    self.logger.error(traceback.format_exc())
                                    self.logger.error(e)

                                if (_cancel_open_orders_list) :
                                    for symbol_l in _cancel_open_orders_list:
                                        for _cancel_open_orders in _cancel_open_orders_list[symbol_l] :
                                            _order_id = _cancel_open_orders['order_id'] 

                                            #判断是成功取消未成交订单
                                            if (_cancel_open_orders) and ('result' in _cancel_open_orders) and (_cancel_open_orders['result'] == True) and ('order_id' in _cancel_open_orders) :
                                                self.logger.info('-----------2-1.取消挂单买入未成交订单成功!: %s-%s' %(symbol_l.upper(),_cancel_open_orders))

                                                #查询指定订单详情获取未成交数量
                                                #{"client_oid": "", "created_at": "2019-04-15T16:43:10.000Z", "filled_notional": "0", "filled_size": "0", "funds": "", "instrument_id": "BTC-USDT", "notional": "", "order_id": "2661455656587264", "order_type": "0", "price": "5120", "product_id": "BTC-USDT", "side": "buy", "size": "0.01", "status": "cancelled", "timestamp": "2019-04-15T16:43:10.000Z", "type": "limit"}
                                                spotAPI = spot.SpotAPI(apiKey, apiSecret, passphrase, True)
                                                order_info_result = spotAPI.get_order_info(symbol_l.upper(), _order_id)
                                                self.logger.info('获取未成交订单信息: %s-%s' %(_order_id,order_info_result))

                                                if (order_info_result) and ('status' in order_info_result) and (order_info_result['status'] != 'filled') :
                                                    if (symbol_l.upper() in tmp_nofilled_volume) :
                                                        tmp_nofilled_volume[symbol_l.upper()] += math.floor((float(order_info_result['size'])-float(order_info_result['filled_size']))*(10**init_precision[symbol_l.upper()]['vol'])+0.1)/(10**init_precision[symbol_l.upper()]['vol'])
                                                    else :
                                                        tmp_nofilled_volume[symbol_l.upper()] = math.floor((float(order_info_result['size'])-float(order_info_result['filled_size']))*(10**init_precision[symbol_l.upper()]['vol'])+0.1)/(10**init_precision[symbol_l.upper()]['vol'])

                                                else :
                                                    self.logger.info('2-2.取消挂单买入未成交订单失败error!: %s-%s' %(symbol_l.upper(),_cancel_open_orders))

                            self.logger.info('获取取消订单统计未成交数据: %s' %(tmp_nofilled_volume))

                            #3.确定当前可用usdt
                            self.logger.debug('3.确定当前可用usdt')
                            spotAPI = spot.SpotAPI(apiKey, apiSecret, passphrase, True)
                            balance_result = spotAPI.get_account_info()
                            if balance_result :
                                for val in balance_result :
                                    if val['currency'] == quote_currency :
                                        #available 可用于交易数量
                                        quote_currency_balance = float(val['available'])

                                if quote_currency in self._position_detail :
                                    tmp_quote_currency_balance = float(self._position_detail[quote_currency]['available'])

                                if quote_currency_balance == tmp_quote_currency_balance :
                                    logger.info('获取当前账户资产成功!quote_currency_balance,tmp_quote_currency_balance: %s,%s' %(quote_currency_balance,tmp_quote_currency_balance))
                                else :
                                    logger.info('获取当前账户资产成功,但存在实时接收数据比对差异,使用查询结果!quote_currency_balance,tmp_quote_currency_balance: %s,%s' %(quote_currency_balance,tmp_quote_currency_balance))
                            else :
                                #参数名	类型	描述
                                #currency	String	币种
                                #balance	String	余额
                                #hold	String	冻结(不可用)
                                #available	String	可用于交易或资金划转的数量
                                #id	String	账户 id
                                if quote_currency in self._position_detail :
                                    quote_currency_balance = float(self._position_detail[quote_currency]['available'])
                                logger.info('获取当前账户资产失败,使用实时接收数据!tmp_quote_currency_balance %s,%s' % (balance_result,quote_currency_balance))

                            #获取到模型实时未成交信息
                            if ('realtime_noopen_volume' in _log_df) and (len(_log_df['realtime_noopen_volume']) > 0) :
                                j = 0 
                                for i in list(range(len(_log_df['realtime_noopen_volume']))) : 
                                    _symbol = _log_df['realtime_noopen_volume'].index[i]

                                    #不等于报价货币的交易币种,或者symbol为''或者symbol需要挂单币种
                                    if (_symbol != quote_currency) and ((symbol == '') or (symbol == _symbol)) and (_symbol in tmp_nofilled_volume) and (tmp_nofilled_volume[_symbol]):

                                        #判断回报的到信息与取消订单统计是否一致,如果不一致按照取消订单统计,有可能回报未下单会大于统计未下单,因为还有其它未下单
                                        if (_log_df['realtime_noopen_volume'][_symbol] != tmp_nofilled_volume[_symbol]) :
                                            self.logger.info('判断回报的取消订单后的未下单信息与取消订单统计是否一致,如果不一致按照取消订单统计_log_df[realtime_noopen_volume][_symbol],tmp_nofilled_volume[_symbol]-%s,%s' %(_log_df['realtime_noopen_volume'][_symbol],tmp_nofilled_volume[_symbol]))

                                        #理论调仓量按照系统要求保留位数舍去取整(正数舍去,负数的绝对值为进1取整)
                                        _now_volume = math.floor(tmp_nofilled_volume[_symbol]*(10**init_precision[_symbol]['vol'])+0.1)/(10**init_precision[_symbol]['vol'])

                                        #判断_now_volume是否大于最小值
                                        if abs(_now_volume) < float(init_precision[_symbol]['min_vol']) :
                                            _now_volume = 0

                                        #close价格按照系统要求保留位数舍去取整
                                        _now_close = math.floor(_log_df['now_close'][i]*(10**init_precision[_symbol]['price'])+0.1)/(10**init_precision[_symbol]['price'])
                                        if _log_df['output_change_volume'][i] > 0 :
                                            _order_type = 'limit'
                                            _order_side = 'buy'
                                            #买挂单-判断取整后小于0交易量
                                            if _now_volume > 0 :
                                                #挂单价格成交
                                                self._resting_single(m_timestamp, _symbol, _now_volume, _now_close, _order_side, _order_type, direction)
                                                j = j+1
                                            #买挂单-判断取整后等于0交易量
                                            elif _now_volume == 0 :
                                                order_result = {'client_oid': '', 'error_code': 'volume-0', 'error_message': 'sell-volume-0', 'order_id': '', 'result': 'error'} 
                                                #解析订单结果
                                                self._orderResult(order_result, m_timestamp, _now_volume, _symbol, _order_type, _order_side, _now_close)

                            else :
                                self.logger.info('3-2.未获取到模型输出的调仓信息:%s' %(_log_df.T))
                    else :
                        #增加查询未成交为为空,清除当前实时未成交订单记录
                        if symbol in self._order_realtime_price_volume :
                            self._order_realtime_price_volume[symbol] = {}


    #追单模块:1.查询所有未成交订单-2.取消未成交订单-3.查询取消的未成交订单-4.进行买卖追单
    #如果symbol=='',取消所有未成交订单;如果symbol为币对代码，会判断仅对此币对进行追单;如果order_side=='',取消买卖所有未成交比对追单,如果sell或buy为仅一种追单
    def _after_single_module(self, m_timestamp, number, symbol , order_side) :
        _open_orders = []
        _open_orders_n = 1
        for symbol_o in symbol_list :
            if (symbol_o != quote_currency) : 
                #获取未成交订单
                spotAPI = spot.SpotAPI(apiKey, apiSecret, passphrase, True)
                _open_orders_s = spotAPI.get_orders_pending('','','',symbol_o)
                if _open_orders_n == 1:
                    if (_open_orders_s) :
                        _open_orders = _open_orders_s[0]
                else :
                    if (_open_orders_s) :
                        _open_orders = _open_orders + _open_orders_s[0]
                _open_orders_n += 1
        _open_orders = [_open_orders]

        #获取未成交订单
        #spotAPI = spot.SpotAPI(apiKey, apiSecret, passphrase, True)
        #_open_orders = spotAPI.get_orders_pending('','','','')
        self.logger.info('第%s次追单-查询对手价格卖出未成交订单: %s' %(number,_open_orders))
        if (_open_orders) and len(_open_orders[0]) > 0 :
            for val in _open_orders[0] :
                _symbol = val['instrument_id']
                #临时未成交交易量 = 下单量-成交量
                tmp_no_deal_volume = 0
                if val['side'] == 'buy' :
                    #临时未成交订单交易量
                    tmp_no_deal_volume = math.floor((float(val['size'])-float(val['filled_size']))*(10**init_precision[_symbol]['vol'])+0.1)/(10**init_precision[_symbol]['vol'])
                elif val['side'] == 'sell' :
                    tmp_no_deal_volume = math.floor((float(val['filled_size'])-float(val['size']))*(10**init_precision[_symbol]['vol'])+0.1)/(10**init_precision[_symbol]['vol'])

                #symbol为''或者symbol存在未成交订单
                if (((symbol == '') or (symbol == _symbol))) and ((order_side == '') or (order_side == val['side'])):
                    #未成交订单交易量要大于等于最小交易量
                    if (abs(tmp_no_deal_volume) >= float(init_precision[_symbol]['min_vol'])) : 
                        _order_id = int(val['order_id'])
                        #close价格按照系统要求保留位数舍去取整
                        _now_close = math.floor(_log_df['now_close'].ix[_symbol]*(10**init_precision[_symbol]['price'])+0.1)/(10**init_precision[_symbol]['price'])

                        try:
                            #取消未成交订单
                            #{"client_oid": "", "error_code": 0, "error_message": {}, "order_id": "2661455656587264", "result": true}
                            #33027 撤单时已经撤销和撤销中的订单不能撤单
                            #{"code":33027,"message":"Order has been revoked or revoked"}, 400
                            _cancel_open_orders = {}
                            spotAPI = spot.SpotAPI(apiKey, apiSecret, passphrase, True)
                            _cancel_open_orders = spotAPI.revoke_order(_order_id,_symbol)

                            self.logger.info('第%s追单-取消对手价格卖出未成交订单: %s-%s' %(number,_symbol,_cancel_open_orders))
                            #判断是成功取消未成交订单
                            if (_cancel_open_orders) and ('result' in _cancel_open_orders) and (_cancel_open_orders['result'] == True) and ('order_id' in _cancel_open_orders) :
                                #查询指定订单详情获取未成交数量
                                #{"client_oid": "", "created_at": "2019-04-15T16:43:10.000Z", "filled_notional": "0", "filled_size": "0", "funds": "", "instrument_id": "BTC-USDT", "notional": "", "order_id": "2661455656587264", "order_type": "0", "price": "5120", "product_id": "BTC-USDT", "side": "buy", "size": "0.01", "status": "cancelled", "timestamp": "2019-04-15T16:43:10.000Z", "type": "limit"}
                                spotAPI = spot.SpotAPI(apiKey, apiSecret, passphrase, True)
                                order_info_result = spotAPI.get_order_info(_symbol, _order_id)
                                self.logger.info('获取未成交订单信息: %s-%s' %(_order_id,order_info_result))
                                if (order_info_result) and ('status' in order_info_result) and (order_info_result['status'] != 'filled') :
                                    _order_type = order_info_result['type'] 
                                    _order_side = order_info_result['side'] 
                                    if _order_side == 'buy' :
                                        _volume = math.floor((float(order_info_result['size'])-float(order_info_result['filled_size']))*(10**init_precision[_symbol]['vol'])+0.1)/(10**init_precision[_symbol]['vol'])
                                    elif _order_side == 'sell' :
                                        _volume = math.floor((float(order_info_result['filled_size'])-float(order_info_result['size']))*(10**init_precision[_symbol]['vol'])+0.1)/(10**init_precision[_symbol]['vol'])

                                    #判断volume是否大于最小值
                                    if abs(_volume) < float(init_precision[_symbol]['min_vol']) :
                                        _volume = 0

                                    if _volume != 0 :
                                        #追单下单
                                        self._after_single_order(m_timestamp, _symbol, _volume, _now_close, _order_side, _order_type)
                            else :
                                self.logger.info('第%s追单-取消对手价格卖出未成交订单失败error!: %s-%s' %(number,_symbol,_cancel_open_orders))
                        except Exception as e:
                            self.logger.error(traceback.format_exc())
                            self.logger.error(e)
                    else :
                        self.logger.info('未成交订单交易量要小于最小交易量: %s-%s' %(tmp_no_deal_volume,val))

        return _open_orders

    #追单下单-买卖单保证有足够的交易量可以快速成交-按照挂单深度大于交易量的对手挂单价位成交
    def _after_single_order(self, m_timestamp, symbol, volume, now_close, order_side, order_type) :
        self.logger.info('_after_single_order-m_timestamp, symbol, volume, now_close, order_side, order_type: %s,%s,%s,%s,%s,%s' % (m_timestamp, symbol, volume, now_close, order_side, order_type))
        #卖追单-使用买单深度报价
        if order_side == 'sell' :
            #买单深度报价
            if (symbol in self._quote) and ('bids' in self._quote[symbol]) :
                self.logger.info('_after_single-leng(bids): %s,%s' % (symbol,len(self._quote[symbol]['bids'])))
                bid_order_price = 0
                bid_order_volume = 0
                bid_total_volume = 0
                order_pre_price = 0
                order_price = 0 
                sell_after_order_limit_ratio = c.SELL_AFTER_ORDER_LIMIT_RATIO
                j = 1
                if len(self._quote[symbol]['bids']) != 0 :
                    i = 1
                    for bid in self._quote[symbol]['bids'] :
                        bid_order_price = math.floor(float(bid[0])*(10**init_precision[symbol]['price'])+0.1)/(10**init_precision[symbol]['price']) 
                        bid_order_volume = math.floor(float(bid[1])*(10**init_precision[symbol]['vol'])+0.1)/(10**init_precision[symbol]['vol'])
                        bid_total_volume += float(bid[1])
                        self.logger.info('_after_single_order-i,symbol,bidPrice,bidVolume,bidtotalVolume: %s,%s,%s,%s,%s' % (i, symbol, float(bid[0]), float(bid[1]), bid_total_volume))
                        #卖单-限制卖的太低价-卖单对手价追单滑点成本 = N档买单报价下单价格对比close价格比率小于等于负千五
                        if (bid_order_price/now_close-1) < sell_after_order_limit_ratio: 
                            #如果买1档价格对比close价格小于卖单价格限制比率,则追单卖价格按照close价格的最低比率价格进行追单
                            if i == 1:
                                order_price = math.floor(now_close*(1+sell_after_order_limit_ratio)*(10**init_precision[symbol]['price'])+0.1)/(10**init_precision[symbol]['price']) 
                                self.logger.info('_after_single_order-order_type, order_side, symbol, volume, order_pirce, now_close: %s,%s,%s,%s,%s,%s' % (order_type, order_side, symbol, abs(volume), order_price, now_close))
                                #下单
                                self._take_order(m_timestamp, order_type, order_side, symbol, abs(volume), 1, '', order_price, '')
                            #如果买N档价格对比close价格小于卖单价格限制比率,则追单卖价格按照前一档价格进行追单
                            else :
                                self.logger.info('_after_single_order-order_type, order_side, symbol, volume, order_pre_pirce, now_close: %s,%s,%s,%s,%s,%s' % (order_type, order_side, symbol, abs(volume), order_pre_price, now_close))
                                #下单
                                self._take_order(m_timestamp, order_type, order_side, symbol, abs(volume), 1, '', order_pre_price, '')
                            j = j+1
                            break
                        else :
                            order_pre_price = bid_order_price 
                        i = i+1

                if j == 1 :
                    order_price = math.floor(now_close*(1+sell_after_order_limit_ratio)*(10**init_precision[symbol]['price'])+0.1)/(10**init_precision[symbol]['price']) 
                    self.logger.info('_after_single_order-order_type, order_side, symbol, volume, order_pirce, now_close: %s,%s,%s,%s,%s,%s' % (order_type, order_side, symbol, abs(volume), order_price, now_close))
                    #下单
                    self._take_order(m_timestamp, order_type, order_side, symbol, abs(volume), 1, '', order_price, '')
            else :
                self.logger.info('_after_single_order-sell-币对未包含深度报价模块! %s,%s' % (symbol, self._quote))
                self.logger.info('_take_order-other-order_type, order_side, symbol, volume, now_close: %s,%s,%s,%s,%s' % (order_type, order_side, symbol, volume, now_close))
                #判断volume是否大于最小值
                if abs(volume) < float(init_precision[symbol]['min_vol']) :
                    volume = 0
                
                if volume != 0 :
                    order_price = math.floor(now_close*(1+sell_after_order_limit_ratio)*(10**init_precision[symbol]['price'])+0.1)/(10**init_precision[symbol]['price']) 
                    #下单
                    self._take_order(m_timestamp, order_type, order_side, symbol, abs(volume), 1, '', order_price, '')

        #买追单-使用卖单深度报价
        elif order_side == 'buy' :
            #卖单深度报价
            if (symbol in self._quote) and ('asks' in self._quote[symbol]) :
                self.logger.info('_after_single-leng(asks): %s,%s' % (symbol,len(self._quote[symbol]['asks'])))
                ask_order_price = 0
                ask_order_volume = 0
                ask_total_volume = 0
                order_pre_price = 0
                order_price = 0 
                buy_after_order_limit_ratio = c.BUY_AFTER_ORDER_LIMIT_RATIO
                j = 1
                if len(self._quote[symbol]['asks']) != 0 :
                    i = 1
                    for ask in self._quote[symbol]['asks'] :
                        ask_order_price = math.floor(float(ask[0])*(10**init_precision[symbol]['price'])+0.1)/(10**init_precision[symbol]['price']) 
                        ask_order_volume = math.floor(float(ask[1])*(10**init_precision[symbol]['vol'])+0.1)/(10**init_precision[symbol]['vol'])
                        ask_total_volume += float(ask[1])
                        self.logger.info('_after_single_order-i,symbol,askPrice,askVolume,asktotalVolume: %s,%s,%s,%s,%s' % (i, symbol, float(ask[0]), float(ask[1]), ask_total_volume))
                        #买单-限制买的太高价-买单对手价追单滑点成本 = N档卖单报价下单价格对比close价格比率大于等于千五
                        if (ask_order_price/now_close-1) > buy_after_order_limit_ratio : 
                            #如果卖1档价格对比close价格大于买单价格限制比率,则追单买价格按照close价格的最高比率价格进行追单
                            if i == 1:
                                order_price = math.floor(now_close*(1+buy_after_order_limit_ratio)*(10**init_precision[symbol]['price'])+0.1)/(10**init_precision[symbol]['price']) 
                                self.logger.info('_after_single_order-1-order_type, order_side, symbol, volume, order_pirce, now_close: %s,%s,%s,%s,%s,%s' % (order_type, order_side, symbol, abs(volume), order_price, now_close))
                                #下单
                                self._take_order(m_timestamp, order_type, order_side, symbol, abs(volume), 1, '', order_price, '')
                            #如果卖N档价格对比close价格小于买单价格限制比率,则追单买价格按照前一档价格进行追单
                            else :
                                self.logger.info('_after_single_order-no1-order_type, order_side, symbol, volume, order_pre_pirce, now_close: %s,%s,%s,%s,%s,%s' % (order_type, order_side, symbol, abs(volume), order_pre_price, now_close))
                                #下单
                                self._take_order(m_timestamp, order_type, order_side, symbol, abs(volume), 1, '', order_pre_price, '')
                            j = j+1
                            break
                        else :
                            order_pre_price = ask_order_price 
                        i = i+1

                if j == 1 :
                    order_price = math.floor(now_close*(1+buy_after_order_limit_ratio)*(10**init_precision[symbol]['price'])+0.1)/(10**init_precision[symbol]['price']) 
                    self.logger.info('_after_single_order-notake-order_type, order_side, symbol, volume, order_pirce, now_close: %s,%s,%s,%s,%s,%s' % (order_type, order_side, symbol, abs(volume), order_price, now_close))
                    #下单
                    self._take_order(m_timestamp, order_type, order_side, symbol, abs(volume), 1, '', order_price, '')
            else :
                self.logger.info('_after_single_order-buy-币对未包含深度报价模块! %s,%s' % (symbol, self._quote))
                self.logger.info('_take_order-other-order_type, order_side, symbol, volume, now_close: %s,%s,%s,%s,%s' % (order_type, order_side, symbol, volume, now_close))
                #判断volume是否大于最小值
                if abs(volume) < float(init_precision[symbol]['min_vol']) :
                    volume = 0
                
                if volume != 0 :
                    order_price = math.floor(now_close*(1+buy_after_order_limit_ratio)*(10**init_precision[symbol]['price'])+0.1)/(10**init_precision[symbol]['price']) 
                    #下单
                    self._take_order(m_timestamp, order_type, order_side, symbol, abs(volume), 1, '', order_price, '')

    #挂单下单-买卖单-maker成交-按照挂单深度大于交易量的买单挂单价位成交
    def _resting_single(self, m_timestamp, symbol, volume, now_close, order_side, order_type, direction) :
        self.logger.info('_resting_single-m_timestamp, symbol, volume, now_close, order_side, order_type: %s,%s,%s,%s,%s,%s' % (m_timestamp, symbol, volume, now_close, order_side, order_type))
        #批量下单参数
        _order_params = []
        #卖挂单-使用卖深度报价
        if order_side == 'sell' :
            #卖报价价格
            ask_order_price = 0
            #卖报价挂单量
            ask_order_volume = 0
            #卖报价总挂单量
            ask_total_volume = 0
            #卖下单总挂单量
            order_total_volume = 0
            #买下单最后挂单量
            order_last_volume = 0
            #默认卖挂单位置,卖挂单默认在close价格之下多少为负
            sell_resting_order_limit_ratio = c.SELL_RESTING_ORDER_LIMIT_RATIO 
            #限制最多挂几档,卖挂单默认9档挂单
            sell_resting_order_limit_level = c.SELL_RESTING_ORDER_LIMIT_LEVEL  

            #使用全量深度卖挂单报价:如果存在增量深度挂单按照10档挂单,否则存在5档全量挂单按照5档挂单,否则按照1档挂单
            if (symbol in self._quote) and ('asks' in self._quote[symbol]) and (len(self._quote[symbol]['asks']) >= 10) :
                self.logger.info('_resting_single-leng(asks): %s,%s' % (symbol,len(self._quote[symbol]['asks'])))
                asks_list = self._quote[symbol]['asks']
            #使用5档深度卖挂单报价:全量深度卖挂单报价小于5个
            elif (symbol in self._quote5) and ('asks' in self._quote5[symbol]) and (len(self._quote5[symbol]['asks']) == 5):
                self.logger.info('asks quote+quote5: %s,%s,%s' % (symbol,self._quote[symbol]['asks'],self._quote5[symbol]['asks']))
                asks_list = self._quote5[symbol]['asks']
                #限制最多挂5档
                sell_resting_order_limit_level = 5 
            #默认挂单close价格挂1档
            else :
                self.logger.info('_resting_single-sell-币对未包含深度报价模块! %s,%s' % (symbol, self._quote))
                asks_list = [[math.floor(now_close*(10**init_precision[symbol]['price'])+1.1)/(10**init_precision[symbol]['price']), abs(volume), 1]] 
                #限制最多挂1档
                sell_resting_order_limit_level = 1 

            #卖挂单的默认挂单价格比率内按照卖1价开始挂单;如果超过默认价格比率又在最小价格比率内按照卖单一档挂单价格/close价格-1的比率内价格挂单;如果小于最小价格比率价格按照最小比率价格挂单
            if float(asks_list[0][0])/now_close-1 >= c.SELL_RESTING_ORDER_LIMIT_RATIO :
                sell_resting_order_limit_ratio = c.SELL_RESTING_ORDER_LIMIT_RATIO 
            elif (float(asks_list[0][0])/now_close-1 < c.SELL_RESTING_ORDER_LIMIT_RATIO) and (float(asks_list[0][0])/now_close-1 >= c.SELL_RESTING_ORDER_LIMIT_RATIO_MAX) :
                sell_resting_order_limit_ratio = float(asks_list[0][0])/now_close-1
            elif (float(asks_list[0][0])/now_close-1 < c.SELL_RESTING_ORDER_LIMIT_RATIO_MAX) :
                sell_resting_order_limit_ratio = c.SELL_RESTING_ORDER_LIMIT_RATIO_MAX

            #挂单方向:前挂单direction='front',后退挂单direction='back'逼近交易价格
            if (direction == 'front') or (direction == '') :
                #1.卖挂单默认大于close价格下单,等待20秒成交
                #2.上涨,容易成交,成交后调整卖2档价格挂单,提升收益; 
                #3.下跌,不容易成交,间隔10秒调整卖1档价格挂单,提升成交速度;
                #4.下跌,保证成交速率不小于1/2,
                #成交速率计算60秒以内,卖单close价格以上挂单
                #20秒内自由成交,20-60秒开始调整挂单位置成交
                ask_order_volume_0 = 0

                if ((m_timestamp-self._start_timestamp) <= 10) :
                    self.logger.info('--------------卖单成交速率--开始N秒内振幅万5以内--大于close价格下单--降低成本--振幅%s' %(float(asks_list[0][0])/now_close-1))
                    #如果距离close价格万5以内,close价格以下挂单
                    if (float(asks_list[0][0])/now_close-1 >= -0.0005) : 
                        sell_resting_order_limit_ratio = 0 
                #大于10秒小于1/2成交时间开始判断成交速率
                elif (m_timestamp-self._start_timestamp > 10) and ((m_timestamp-self._start_timestamp) <= (self._cancel_order_timestamp-self._start_timestamp)/2) :
                    #判断成交速率大于1,close价格以下下单
                    if ('realtime_change_volume' in _log_df) and (symbol in _log_df['realtime_change_volume']) and ('floor_change_volume' in _log_df) and (symbol in _log_df['floor_change_volume']) and (abs(_log_df['realtime_change_volume'][symbol]/(m_timestamp-self._start_timestamp))/abs(_log_df['floor_change_volume'][symbol]/(self._cancel_order_timestamp-self._start_timestamp)) >= 1): 
                        self.logger.info('--------------卖单成交速率--上半段交易时间--成交速率大于等于1--距离close价格万5以内--大于close价格下单--降低成本--振幅%s' %(float(asks_list[0][0])/now_close-1))
                        #如果距离close价格万5以内,close价格以下挂单
                        if (float(asks_list[0][0])/now_close-1 >= -0.0005) : 
                            sell_resting_order_limit_ratio = 0 
                    #判断成交速率小于1,追单到速率0.5,速率1,速率2,币种交易量的50%
                    elif ('realtime_change_volume' in _log_df) and (symbol in _log_df['realtime_change_volume']) and ('floor_change_volume' in _log_df) and (symbol in _log_df['floor_change_volume']) and (abs(_log_df['realtime_change_volume'][symbol]/(m_timestamp-self._start_timestamp))/abs(_log_df['floor_change_volume'][symbol]/(self._cancel_order_timestamp-self._start_timestamp)) < 1) : 
                        self.logger.info('卖单成交速率--上半段交易时间--成交速率小于1--根据振幅调整挂单价格和对手价价格追单--提高成交速率-symbol,实时已成交量,需成交量,每秒已成交量,每秒需成交量,每秒已成交量/每秒需成交量-%s,%s,%s,%s,%s,%s' %(symbol,_log_df['realtime_change_volume'][symbol],_log_df['floor_change_volume'][symbol],(_log_df['realtime_change_volume'][symbol]/(m_timestamp-self._start_timestamp)),(_log_df['floor_change_volume'][symbol]/(self._cancel_order_timestamp-self._start_timestamp)),abs(_log_df['realtime_change_volume'][symbol]/(m_timestamp-self._start_timestamp))/abs(_log_df['floor_change_volume'][symbol]/(self._cancel_order_timestamp-self._start_timestamp))))
                        if (float(asks_list[0][0])/now_close-1 >= -0.0005) : 
                            self.logger.info('卖单成交速率--上半段交易时间--成交速率小于1--距离close价格万5以内--对手价+1个单位进行挂单--提高成交速率-symbol,实时已成交量,需成交量,每秒已成交量,每秒需成交量,每秒已成交量/每秒需成交量-%s,%s,%s,%s,%s,%s' %(symbol,_log_df['realtime_change_volume'][symbol],_log_df['floor_change_volume'][symbol],(_log_df['realtime_change_volume'][symbol]/(m_timestamp-self._start_timestamp)),(_log_df['floor_change_volume'][symbol]/(self._cancel_order_timestamp-self._start_timestamp)),abs(_log_df['realtime_change_volume'][symbol]/(m_timestamp-self._start_timestamp))/abs(_log_df['floor_change_volume'][symbol]/(self._cancel_order_timestamp-self._start_timestamp))))
                            if (self._quote[symbol]['bids']) and (self._quote[symbol]['asks']) :
                                #卖1档之上下单价格:买1档+一个单位价格
                                ask_order_price_0 = math.floor(float(self._quote[symbol]['bids'][0][0])*(10**init_precision[symbol]['price'])+1.1)/(10**init_precision[symbol]['price']) 
                                #如果下单价格小于等于买1档且大于卖1档进行下单
                                if (ask_order_price_0 > float(self._quote[symbol]['bids'][0][0])) and (ask_order_price_0 < float(self._quote[symbol]['asks'][0][0])) :
                                    self.logger.info('如果下单价格小于卖1档且大于买1档进行下单float(symbol,self._quote[symbol][bids][0][0]),ask_order_price_0,float(self._quote[symbol][asks][0][0])-%s,%s,%s,%s' %(symbol,float(self._quote[symbol]['bids'][0][0]),ask_order_price_0,float(self._quote[symbol]['asks'][0][0])))
                                    if abs(volume) >= (abs(_log_df['floor_change_volume'][symbol])/sell_resting_order_limit_level) :
                                        #实际挂单量算法,10分之一的总调仓量
                                        ask_order_volume_0 = math.floor((abs(_log_df['floor_change_volume'][symbol])/sell_resting_order_limit_level)*(10**init_precision[symbol]['vol'])+0.1)/(10**init_precision[symbol]['vol'])
                                    else :
                                        #实际挂单量算法,当前调仓量
                                        ask_order_volume_0 = math.floor(abs(volume)*(10**init_precision[symbol]['vol'])+0.1)/(10**init_precision[symbol]['vol'])
                        #如果距离close价格千1以内,追单到速率1
                        elif (float(asks_list[0][0])/now_close-1 < -0.0005) and (float(asks_list[0][0])/now_close-1 >= -0.001) : 
                            ask_order_price_0 = math.floor((now_close*(1+c.SELL_AFTER_ORDER_LIMIT_RATIO))*(10**init_precision[symbol]['price'])+0.1)/(10**init_precision[symbol]['price']) 
                            ask_order_volume_0 = math.floor((1*abs(_log_df['floor_change_volume'][symbol])*(m_timestamp-self._start_timestamp)/(self._cancel_order_timestamp-self._start_timestamp)-abs(_log_df['realtime_change_volume'][symbol]))*(10**init_precision[symbol]['vol'])+0.1)/(10**init_precision[symbol]['vol'])
                            self.logger.info('--------------卖单成交速率--上半段交易时间--成交速率小于1--距离close价格小千1以内,追单到速率1--提升成交速率-symbol,ask_order_price_0,ask_order_volume_0-%s,%s,%s' %(symbol,ask_order_price_0,ask_order_volume_0))
                        #如果距离close价格千2以内,追单到速率2
                        elif (float(asks_list[0][0])/now_close-1 < -0.001) and (float(asks_list[0][0])/now_close-1 >= -0.002) :
                            ask_order_price_0 = math.floor((now_close*(1+c.SELL_AFTER_ORDER_LIMIT_RATIO))*(10**init_precision[symbol]['price'])+0.1)/(10**init_precision[symbol]['price']) 
                            ask_order_volume_0 = math.floor((2*abs(_log_df['floor_change_volume'][symbol])*(m_timestamp-self._start_timestamp)/(self._cancel_order_timestamp-self._start_timestamp)-abs(_log_df['realtime_change_volume'][symbol]))*(10**init_precision[symbol]['vol'])+0.1)/(10**init_precision[symbol]['vol'])
                            self.logger.info('--------------卖单成交速率--上半段交易时间--成交速率小于1--距离close价格小千2以内,追单到速率2--提升成交速率-symbol,ask_order_price_0,ask_order_volume_0-%s,%s,%s' %(symbol,ask_order_price_0,ask_order_volume_0))
                        #如果距离close价格千3以内,追单到币种交易量的50%
                        elif (float(asks_list[0][0])/now_close-1 < -0.002) and (float(asks_list[0][0])/now_close-1 >= -0.003) :
                            ask_order_price_0 = math.floor((now_close*(1+c.SELL_AFTER_ORDER_LIMIT_RATIO))*(10**init_precision[symbol]['price'])+0.1)/(10**init_precision[symbol]['price']) 
                            ask_order_volume_0 = math.floor((0.5*abs(_log_df['floor_change_volume'][symbol])-abs(_log_df['realtime_change_volume'][symbol]))*(10**init_precision[symbol]['vol'])+0.1)/(10**init_precision[symbol]['vol'])
                            self.logger.info('--------------卖单成交速率--上半段交易时间--成交速率小于1--距离close价格小千3以内,追单到币种交易量的百分之50--提升成交速率-symbol,ask_order_price_0,ask_order_volume_0-%s,%s,%s' %(symbol,ask_order_price_0,ask_order_volume_0))
                        #如果距离close价格千4以内,追单到币种交易量的60%
                        elif (float(asks_list[0][0])/now_close-1 < -0.003) and (float(asks_list[0][0])/now_close-1 >= -0.004) :
                            ask_order_price_0 = math.floor((now_close*(1+c.SELL_AFTER_ORDER_LIMIT_RATIO))*(10**init_precision[symbol]['price'])+0.1)/(10**init_precision[symbol]['price']) 
                            ask_order_volume_0 = math.floor((0.6*abs(_log_df['floor_change_volume'][symbol])-abs(_log_df['realtime_change_volume'][symbol]))*(10**init_precision[symbol]['vol'])+0.1)/(10**init_precision[symbol]['vol'])
                            self.logger.info('--------------卖单成交速率--上半段交易时间--成交速率小于1--距离close价格小千4以内,追单到币种交易量的百分之60--提升成交速率-symbol,ask_order_price_0,ask_order_volume_0-%s,%s,%s' %(symbol,ask_order_price_0,ask_order_volume_0))
                        #如果距离close价格千5以内,追单到币种交易量的70%
                        elif (float(asks_list[0][0])/now_close-1 < -0.004) and (float(asks_list[0][0])/now_close-1 >= -0.005) :
                            ask_order_price_0 = math.floor((now_close*(1+c.SELL_AFTER_ORDER_LIMIT_RATIO))*(10**init_precision[symbol]['price'])+0.1)/(10**init_precision[symbol]['price']) 
                            ask_order_volume_0 = math.floor((0.7*abs(_log_df['floor_change_volume'][symbol])-abs(_log_df['realtime_change_volume'][symbol]))*(10**init_precision[symbol]['vol'])+0.1)/(10**init_precision[symbol]['vol'])
                            self.logger.info('--------------卖单成交速率--上半段交易时间--成交速率小于1--距离close价格小千5以内,追单到币种交易量的百分之70--提升成交速率-symbol,ask_order_price_0,ask_order_volume_0-%s,%s,%s' %(symbol,ask_order_price_0,ask_order_volume_0))
                        #如果距离close价格千5以外,追单到币种交易量的80%
                        elif (float(asks_list[0][0])/now_close-1 < -0.005) :
                            ask_order_price_0 = math.floor((now_close*(1+c.SELL_AFTER_ORDER_LIMIT_RATIO))*(10**init_precision[symbol]['price'])+0.1)/(10**init_precision[symbol]['price']) 
                            ask_order_volume_0 = math.floor((0.8*abs(_log_df['floor_change_volume'][symbol])-abs(_log_df['realtime_change_volume'][symbol]))*(10**init_precision[symbol]['vol'])+0.1)/(10**init_precision[symbol]['vol'])
                            self.logger.info('--------------卖单成交速率--上半段交易时间--成交速率小于1--距离close价格小千5以外,追单到币种交易量的百分之80--提升成交速率-symbol,ask_order_price_0,ask_order_volume_0-%s,%s,%s' %(symbol,ask_order_price_0,ask_order_volume_0))

                #大于总成交的一半时间,开始提升成交速率
                elif ((m_timestamp-self._start_timestamp) > (self._cancel_order_timestamp-self._start_timestamp)/2) :
                    if ('realtime_change_volume' in _log_df) and (symbol in _log_df['realtime_change_volume']) and ('floor_change_volume' in _log_df) and (symbol in _log_df['floor_change_volume']) and (abs(_log_df['realtime_change_volume'][symbol]/(m_timestamp-self._start_timestamp))/abs(_log_df['floor_change_volume'][symbol]/(self._cancel_order_timestamp-self._start_timestamp)) < 1.5) : 
                        self.logger.info('卖单成交速率--超过下单一半时间-小于1.5倍--根据振幅调整挂单价格和对手价价格追单--提高成交速率-symbol,实时已成交量,需成交量,每秒已成交量,每秒需成交量,每秒已成交量/每秒需成交量-%s,%s,%s,%s,%s,%s' %(symbol,_log_df['realtime_change_volume'][symbol],_log_df['floor_change_volume'][symbol],(_log_df['realtime_change_volume'][symbol]/(m_timestamp-self._start_timestamp)),(_log_df['floor_change_volume'][symbol]/(self._cancel_order_timestamp-self._start_timestamp)),abs(_log_df['realtime_change_volume'][symbol]/(m_timestamp-self._start_timestamp))/abs(_log_df['floor_change_volume'][symbol]/(self._cancel_order_timestamp-self._start_timestamp))))
                        #如果距离close价格千1以内,追单到速率1.5
                        if (float(asks_list[0][0])/now_close-1 >= -0.001) :
                            ask_order_price_0 = math.floor((now_close*(1+c.SELL_AFTER_ORDER_LIMIT_RATIO))*(10**init_precision[symbol]['price'])+0.1)/(10**init_precision[symbol]['price']) 
                            ask_order_volume_0 = math.floor((1.5*abs(_log_df['floor_change_volume'][symbol])*(m_timestamp-self._start_timestamp)/(self._cancel_order_timestamp-self._start_timestamp)-abs(_log_df['realtime_change_volume'][symbol]))*(10**init_precision[symbol]['vol'])+0.1)/(10**init_precision[symbol]['vol'])
                            self.logger.info('--------------卖单成交速率--超过下单一半时间--距离close价格小千1以内,追单到速率1.25--提升成交速率-symbol,ask_order_price_0,ask_order_volume_0-%s,%s,%s' %(symbol,ask_order_price_0,ask_order_volume_0))
                        #如果距离close价格千2以内,追单到币种交易量的80%
                        elif (float(asks_list[0][0])/now_close-1 < -0.001) and (float(asks_list[0][0])/now_close-1 >= -0.002) :
                            ask_order_price_0 = math.floor((now_close*(1+c.SELL_AFTER_ORDER_LIMIT_RATIO))*(10**init_precision[symbol]['price'])+0.1)/(10**init_precision[symbol]['price']) 
                            ask_order_volume_0 = math.floor((0.8*abs(_log_df['floor_change_volume'][symbol])-abs(_log_df['realtime_change_volume'][symbol]))*(10**init_precision[symbol]['vol'])+0.1)/(10**init_precision[symbol]['vol'])
                            self.logger.info('--------------卖单成交速率--超过下单一半时间--距离close价格小千2以内,追单到币种交易量的百分之80--提升成交速率-symbol,ask_order_price_0,ask_order_volume_0-%s,%s,%s' %(symbol,ask_order_price_0,ask_order_volume_0))
                        #如果距离close价格千3以内,追单到币种交易量的90%
                        elif (float(asks_list[0][0])/now_close-1 < -0.002) and (float(asks_list[0][0])/now_close-1 >= -0.003) :
                            ask_order_price_0 = math.floor((now_close*(1+c.SELL_AFTER_ORDER_LIMIT_RATIO))*(10**init_precision[symbol]['price'])+0.1)/(10**init_precision[symbol]['price']) 
                            ask_order_volume_0 = math.floor((0.9*abs(_log_df['floor_change_volume'][symbol])-abs(_log_df['realtime_change_volume'][symbol]))*(10**init_precision[symbol]['vol'])+0.1)/(10**init_precision[symbol]['vol'])
                            self.logger.info('--------------卖单成交速率--超过下单一半时间--距离close价格小千3以内,追单到币种交易量的百分之90--提升成交速率-symbol,ask_order_price_0,ask_order_volume_0-%s,%s,%s' %(symbol,ask_order_price_0,ask_order_volume_0))
                        #如果距离close价格千3以外,追单到币种交易量的100%
                        elif (float(asks_list[0][0])/now_close-1 < -0.003) :
                            ask_order_price_0 = math.floor((now_close*(1+c.SELL_AFTER_ORDER_LIMIT_RATIO))*(10**init_precision[symbol]['price'])+0.1)/(10**init_precision[symbol]['price']) 
                            ask_order_volume_0 = math.floor((1*abs(_log_df['floor_change_volume'][symbol])-abs(_log_df['realtime_change_volume'][symbol]))*(10**init_precision[symbol]['vol'])+0.1)/(10**init_precision[symbol]['vol'])
                            self.logger.info('--------------卖单成交速率--超过下单一半时间--距离close价格小千3以外,追单到币种交易量的百分之100--提升成交速率-symbol,ask_order_price_0,ask_order_volume_0-%s,%s,%s' %(symbol,ask_order_price_0,ask_order_volume_0))

                #判断volume是否大于最小值
                if abs(ask_order_volume_0) < float(init_precision[symbol]['min_vol']) :
                    ask_order_volume_0 = 0

                if ask_order_volume_0 != 0 :
                    self.logger.info('_resting_single-i,symbol,askPrice,askVolume,asktotalVolume,ask_order_price,ask_order_volume: %s,%s,%s,%s,%s,%s,%s' % (0, symbol, ask_order_price_0, ask_order_volume_0, ask_order_volume_0, ask_order_price_0, ask_order_volume_0))

                    #下单 margin_trading	String	1 币币交易订单. 2 杠杆交易订单 order_type	String	0：普通委托 1：只做Maker（Post only） 2：全部成交或立即取消（FOK） 3：立即成交并取消剩余（IOC）
                    #self._take_order(m_timestamp, order_type, order_side, symbol, ask_order_volume_0, 1, '', ask_order_price_0, '')
                    _order_params.append({'client_oid': 'id'+str(m_timestamp)+'0', 'instrument_id': symbol, 'side': order_side, 'type': order_type, 'size': ask_order_volume_0, 'price': ask_order_price_0, 'margin_trading': 1})
                    volume += ask_order_volume_0
            elif (direction == 'back') :
                sell_resting_order_limit_ratio = float(asks_list[c.SELL_RESTING_ORDER_LIMIT_POSITION_BACK][0])/now_close-1

            self.logger.info('symbol,sell_resting_order_limit_ratio,asks_list[0][0],now_close: %s,%s,%s,%s' % (symbol, sell_resting_order_limit_ratio,float(asks_list[0][0]),now_close)) 

            #计算N档卖挂单的挂单总量
            #卖N档下单总挂单量
            order_total_volume_n = 0
            n = 1
            for ask in asks_list:
                if n > sell_resting_order_limit_level :
                    break
                order_total_volume_n += float(ask[1])
                n = n+1

            i = 1
            j = 1
            for ask in asks_list:
                ask_order_price = math.floor(float(ask[0])*(10**init_precision[symbol]['price'])+0.1)/(10**init_precision[symbol]['price']) 
                #1.当前深度各价格挂单量+n档价格分之一的成交量
                if c.SELL_RESTING_ORDER_METHOD_ID == 1 :
                    #实际挂单量算法,当前价格深度挂单量+10分之一的成交量
                    ask_order_volume = math.floor((float(ask[1])+abs(volume)/sell_resting_order_limit_level)*(10**init_precision[symbol]['vol'])+0.1)/(10**init_precision[symbol]['vol'])
                #2.当前深度各价格挂单量比率
                elif c.SELL_RESTING_ORDER_METHOD_ID == 2 :
                    ask_order_volume = math.floor(((float(ask[1])/order_total_volume_n)*abs(volume))*(10**init_precision[symbol]['vol'])+0.1)/(10**init_precision[symbol]['vol'])
                #3.总调仓量的n档价格分之一的成交量
                elif c.SELL_RESTING_ORDER_METHOD_ID == 3 :
                    #实际挂单量算法,10分之一的总调仓量
                    ask_order_volume = math.floor((abs(_log_df['floor_change_volume'][symbol])/sell_resting_order_limit_level)*(10**init_precision[symbol]['vol'])+0.1)/(10**init_precision[symbol]['vol'])
                else :
                    #实际挂单量算法,当前价格深度挂单量+10分之一的成交量
                    ask_order_volume = math.floor((float(ask[1])+abs(volume)/sell_resting_order_limit_level)*(10**init_precision[symbol]['vol'])+0.1)/(10**init_precision[symbol]['vol'])

                #如果挂单量小于最小挂单量,则替换为最小挂单量下单
                if abs(ask_order_volume) < float(init_precision[symbol]['min_vol']):
                    ask_order_volume = float(init_precision[symbol]['min_vol'])

                ask_total_volume += float(ask[1])
                self.logger.info('_resting_single-i,symbol,askPrice,askVolume,asktotalVolume,ask_order_price,ask_order_volume: %s,%s,%s,%s,%s,%s,%s' % (i, symbol, float(ask[0]), float(ask[1]), ask_total_volume, ask_order_price, ask_order_volume))
                #卖单挂单-调节卖单挂单价格位置,当前判断大于close报价按照卖单深度报价交易量挂单,平均挂多少档sell_level
                if ask_order_price > now_close*(1+sell_resting_order_limit_ratio) :
                    order_total_volume += ask_order_volume

                    #如果卖单第一挂单价格等于当前挂单最小值
                    #if (j == 1) and (symbol in self._order_realtime_price_volume) and (self._order_realtime_price_volume[symbol]) and (ask_order_price == min(self._order_realtime_price_volume[symbol])) :
                    #    self.logger.info('卖单下单1档价格等于当前持仓最小价格卖单,不进行调仓-: %s,%s,%s' % (symbol, ask_order_price, min(self._order_realtime_price_volume[symbol])))
                    #    break

                    #深度报价交易量加和大于交易量绝对值时N-1档对手报价
                    if (abs(order_total_volume) + float(init_precision[symbol]['min_vol'])) >= abs(volume) :
                        if j == 1 :
                            self.logger.info('_take_order-j-order_type, order_side, symbol, volume, ask_order_pirce, now_close, order_total_volume: %s,%s,%s,%s,%s,%s,%s' % (order_type, order_side, symbol, abs(volume), ask_order_price, now_close, order_total_volume))
                            #判断volume是否大于最小值
                            if abs(volume) < float(init_precision[symbol]['min_vol']) :
                                volume = 0

                            if volume != 0 :
                                #下单
                                #self._take_order(m_timestamp, order_type, order_side, symbol, abs(volume), 1, '', ask_order_price, '')
                                _order_params.append({'client_oid': 'id'+str(m_timestamp)+str(i), 'instrument_id': symbol, 'side': order_side, 'type': order_type, 'size': abs(volume), 'price': ask_order_price, 'margin_trading': 1})
                            else :
                                order_result = {'client_oid': '', 'error_code': 'volume-0', 'error_message': 'volume-0', 'order_id': '', 'result': 'error'} 
                                #解析订单结果
                                self._orderResult(order_result, m_timestamp, abs(volume), symbol, order_type, order_side, ask_order_price)
                        else :
                            order_last_volume = math.floor((abs(volume)-order_total_volume+ask_order_volume)*(10**init_precision[symbol]['vol'])+0.1)/(10**init_precision[symbol]['vol']) 
                            self.logger.info('_take_order-nj-order_type, order_side, symbol, volume, ask_order_pirce, now_close, order_total_volume: %s,%s,%s,%s,%s,%s,%s' % (order_type, order_side, symbol, abs(volume), ask_order_price, now_close, order_total_volume))
                            #判断volume是否大于最小值
                            if abs(order_last_volume) < float(init_precision[symbol]['min_vol']) :
                                order_last_volume = 0

                            if order_last_volume != 0 :
                                #下单
                                #self._take_order(m_timestamp, order_type, order_side, symbol, order_last_volume, 1, '', ask_order_price, '')
                                _order_params.append({'client_oid': 'id'+str(m_timestamp)+str(i), 'instrument_id': symbol, 'side': order_side, 'type': order_type, 'size': order_last_volume, 'price': ask_order_price, 'margin_trading': 1})
                            else :
                                order_result = {'client_oid': '', 'error_code': 'volume-0', 'error_message': 'volume-0', 'order_id': '', 'result': 'error'} 
                                #解析订单结果
                                self._orderResult(order_result, m_timestamp, order_last_volume, symbol, order_type, order_side, ask_order_price)
                        break
                    else :
                        self.logger.info('_take_order-order_type, order_side, symbol, volume, ask_order_pirce, now_close, order_total_volume: %s,%s,%s,%s,%s,%s,%s' % (order_type, order_side, symbol, abs(volume), ask_order_price, now_close, order_total_volume))

                        #判断volume是否大于最小值
                        if abs(ask_order_volume) < float(init_precision[symbol]['min_vol']) :
                            ask_order_volume = 0

                        if ask_order_volume != 0 :
                            #下单
                            #self._take_order(m_timestamp, order_type, order_side, symbol, ask_order_volume, 1, '', ask_order_price, '')
                            _order_params.append({'client_oid': 'id'+str(m_timestamp)+str(i), 'instrument_id': symbol, 'side': order_side, 'type': order_type, 'size': ask_order_volume, 'price': ask_order_price, 'margin_trading': 1})
                        else :
                            order_result = {'client_oid': '', 'error_code': 'volume-0', 'error_message': 'volume-0', 'order_id': '', 'result': 'error'} 
                            #解析订单结果
                            self._orderResult(order_result, m_timestamp, ask_order_volume, symbol, order_type, order_side, ask_order_price)
                    j = j+1
                i = i+1
            if _order_params :
                #批量下单
                self._take_orders(m_timestamp, _order_params)

        #买挂单-使用买深度报价
        elif order_side == 'buy' :
            #买报价价格
            bid_order_price = 0
            #买报价挂单量
            bid_order_volume = 0
            #买报价总挂单量
            bid_total_volume = 0
            #买下单总挂单量
            order_total_volume = 0
            #买下单最后挂单量
            order_last_volume = 0
            #默认买挂单位置,买挂单默认在close价格之上多少为正
            buy_resting_order_limit_ratio = c.BUY_RESTING_ORDER_LIMIT_RATIO 
            #限制最多挂几档,买挂单默认10档挂单
            buy_resting_order_limit_level = c.BUY_RESTING_ORDER_LIMIT_LEVEL 

            #使用全量深度买挂单报价:如果存在增量深度挂单按照10档挂单,否则存在5档全量挂单按照5档挂单,否则按照1档挂单
            if (symbol in self._quote) and ('bids' in self._quote[symbol]) and (len(self._quote[symbol]['bids']) >= 10) :
                self.logger.info('_resting_single-leng(bids): %s,%s' % (symbol,len(self._quote[symbol]['bids'])))
                bids_list = self._quote[symbol]['bids']
            #使用5档深度卖挂单报价:全量深度卖挂单报价小于5个
            elif (symbol in self._quote5) and ('bids' in self._quote5[symbol]) and (len(self._quote5[symbol]['bids']) == 5):
                self.logger.info('bids quote+quote5: %s,%s,%s' % (symbol,self._quote[symbol]['bids'],self._quote5[symbol]['bids']))
                bids_list = self._quote5[symbol]['bids']
                #限制最多挂5档
                buy_resting_order_limit_level = 5 
            #默认挂单close价格挂1档
            else :
                self.logger.info('_resting_single-buy-币对未包含深度报价模块! %s,%s' % (symbol, self._quote))
                bids_list = [[math.floor(now_close*(10**init_precision[symbol]['price'])-1.1)/(10**init_precision[symbol]['price']), abs(volume), 1]] 
                #限制最多挂1档
                buy_resting_order_limit_level = 1 

            #买挂单的默认挂单价格比率内按照买1价开始挂单;如果超过默认价格比率又在最大价格比率内按照买单一档挂单价格/close价格的比率价格挂单;如果大于最大价格比率按照最大比率价格下单
            if float(bids_list[0][0])/now_close-1 > c.BUY_RESTING_ORDER_LIMIT_RATIO :
                buy_resting_order_limit_ratio = c.BUY_RESTING_ORDER_LIMIT_RATIO 
            elif (float(bids_list[0][0])/now_close-1 > c.BUY_RESTING_ORDER_LIMIT_RATIO) and (float(bids_list[0][0])/now_close-1 <= c.BUY_RESTING_ORDER_LIMIT_RATIO_MAX) :
                buy_resting_order_limit_ratio = float(bids_list[0][0])/now_close-1
            elif (float(bids_list[0][0])/now_close-1 > c.BUY_RESTING_ORDER_LIMIT_RATIO_MAX) :
                buy_resting_order_limit_ratio = c.BUY_RESTING_ORDER_LIMIT_RATIO_MAX

            #挂单方向:前挂单direction='front',后推挂单direction='back'逼近交易价格
            if (direction == 'front') or (direction == '') :
                #20秒内close价格挂单等待成交,20-60秒根据报价深度价格调整挂单位置成交
                bid_order_volume_0 = 0

                if ((m_timestamp-self._start_timestamp) <= 30) :
                    self.logger.info('--------------买单成交速率--开始N秒内振幅万5以内--小于close价格下单--降低成本--振幅%s' %(float(bids_list[0][0])/now_close-1))
                    #如果距离close价格万5以内,close价格以下挂单
                    if (float(bids_list[0][0])/now_close-1 <= 0.0005) : 
                        buy_resting_order_limit_ratio = 0 
                #小于一半交易时间
                elif (m_timestamp-self._start_timestamp > 30) and ((m_timestamp-self._start_timestamp) <= (self._cancel_order_timestamp-self._start_timestamp)/2):
                    #判断成交速率大于1,close价格以下下单
                    #总执行时间38分钟,10分之一就是3.8分钟,执行速率大于4倍就是1分钟之内执行完1/10可以适当调节挂单价格
                    if ('realtime_change_volume' in _log_df) and (symbol in _log_df['realtime_change_volume']) and ('floor_change_volume' in _log_df) and (symbol in _log_df['floor_change_volume']) and (abs(_log_df['realtime_change_volume'][symbol]/(m_timestamp-self._start_timestamp))/abs(_log_df['floor_change_volume'][symbol]/(self._cancel_order_timestamp-self._start_timestamp)) >= 1) :
                        self.logger.info('买单成交速率--当前下单时间一半交易时间内--大于1倍--close价格以上挂单--降低成本-symbol,实时已成交量,需成交量,每秒已成交量,每秒需成交量,每秒已成交量/每秒需成交量,振幅-%s,%s,%s,%s,%s,%s,%s' %(symbol,_log_df['realtime_change_volume'][symbol],_log_df['floor_change_volume'][symbol],(_log_df['realtime_change_volume'][symbol]/(m_timestamp-self._start_timestamp)),(_log_df['floor_change_volume'][symbol]/(self._cancel_order_timestamp-self._start_timestamp)),abs(_log_df['realtime_change_volume'][symbol]/(m_timestamp-self._start_timestamp))/abs(_log_df['floor_change_volume'][symbol]/(self._cancel_order_timestamp-self._start_timestamp)),(float(bids_list[0][0])/now_close-1)))
                        if (float(bids_list[0][0])/now_close-1 <= 0.002) : 
                            #成交速率大于等于4
                            if (abs(_log_df['realtime_change_volume'][symbol]/(m_timestamp-self._start_timestamp))/abs(_log_df['floor_change_volume'][symbol]/(self._cancel_order_timestamp-self._start_timestamp)) >= 4) :
                                self.logger.info('--------------买单成交速率大于4--当前下单时间一半交易时间内--距离close价格千分之0.5以外,挂单在千0.5以下--降低成本-symbol,buy_resting_order_limit_ratio-%s,%s' %(symbol,buy_resting_order_limit_ratio))
                                if (float(bids_list[0][0])/now_close-1 <= 0) :
                                    buy_resting_order_limit_ratio = float(bids_list[3][0])/now_close-1 
                                elif (float(bids_list[0][0])/now_close-1 <= 0.001) and (float(bids_list[0][0])/now_close-1 > 0) :
                                    buy_resting_order_limit_ratio = 0 
                            #成交速率大于等于3
                            elif (abs(_log_df['realtime_change_volume'][symbol]/(m_timestamp-self._start_timestamp))/abs(_log_df['floor_change_volume'][symbol]/(self._cancel_order_timestamp-self._start_timestamp)) >= 3) and (abs(_log_df['realtime_change_volume'][symbol]/(m_timestamp-self._start_timestamp))/abs(_log_df['floor_change_volume'][symbol]/(self._cancel_order_timestamp-self._start_timestamp)) < 4) :
                                self.logger.info('--------------买单成交速率大于3--当前下单时间一半交易时间内--距离close价格千分之0.5以外,挂单在千0.5以下--降低成本-symbol,buy_resting_order_limit_ratio-%s,%s' %(symbol,buy_resting_order_limit_ratio))
                                if (float(bids_list[0][0])/now_close-1 <= 0) :
                                    buy_resting_order_limit_ratio = float(bids_list[2][0])/now_close-1 
                                elif (float(bids_list[0][0])/now_close-1 <= 0.001) and (float(bids_list[0][0])/now_close-1 > 0) :
                                    buy_resting_order_limit_ratio = 0 
                            #成交速率大于等于2
                            elif (abs(_log_df['realtime_change_volume'][symbol]/(m_timestamp-self._start_timestamp))/abs(_log_df['floor_change_volume'][symbol]/(self._cancel_order_timestamp-self._start_timestamp)) >= 2) and (abs(_log_df['realtime_change_volume'][symbol]/(m_timestamp-self._start_timestamp))/abs(_log_df['floor_change_volume'][symbol]/(self._cancel_order_timestamp-self._start_timestamp)) < 3):
                                self.logger.info('--------------买单成交速率大于2--当前下单时间一半交易时间内--距离close价格千分之0.5以外,挂单在千0.5以下--降低成本-symbol,buy_resting_order_limit_ratio-%s,%s' %(symbol,buy_resting_order_limit_ratio))
                                if (float(bids_list[0][0])/now_close-1 <= 0) :
                                    buy_resting_order_limit_ratio = float(bids_list[1][0])/now_close-1 
                                elif (float(bids_list[0][0])/now_close-1 <= 0.001) and (float(bids_list[0][0])/now_close-1 > 0) :
                                    buy_resting_order_limit_ratio = 0 
                            else :
                                self.logger.info('买单成交速率--当前下单时间一半交易时间内--大于1倍-距离close价格千5以内--对手价+1个单位进行挂单--提高成交速率-symbol,实时已成交量,需成交量,每秒已成交量,每秒需成交量,每秒已成交量/每秒需成交量-%s,%s,%s,%s,%s,%s' %(symbol,_log_df['realtime_change_volume'][symbol],_log_df['floor_change_volume'][symbol],(_log_df['realtime_change_volume'][symbol]/(m_timestamp-self._start_timestamp)),(_log_df['floor_change_volume'][symbol]/(self._cancel_order_timestamp-self._start_timestamp)),abs(_log_df['realtime_change_volume'][symbol]/(m_timestamp-self._start_timestamp))/abs(_log_df['floor_change_volume'][symbol]/(self._cancel_order_timestamp-self._start_timestamp))))
                                if (float(bids_list[0][0])/now_close-1 <= 0.0005) :
                                    buy_resting_order_limit_ratio = 0 
                        elif (float(bids_list[0][0])/now_close-1 <= 0.005) and (float(bids_list[0][0])/now_close-1 > 0.002) : 
                            if (self._quote[symbol]['bids']) and (self._quote[symbol]['asks']) :
                                #买1档之之下下单价格:卖1档-一个单位价格
                                bid_order_price_0 = math.floor(float(self._quote[symbol]['asks'][0][0])*(10**init_precision[symbol]['price'])-0.9)/(10**init_precision[symbol]['price']) 
                                #如果下单价格小于卖1档且大于买1档进行下单
                                if (bid_order_price_0 > float(self._quote[symbol]['bids'][0][0])) and (bid_order_price_0 < float(self._quote[symbol]['asks'][0][0])) :
                                    self.logger.info('如果下单价格小于卖1档且大于买1档进行下单float(self._quote[symbol][bids][0][0]),bid_order_price_0,float(self._quote[symbol][asks][0][0]),-%s,%s,%s' %(float(self._quote[symbol]['bids'][0][0]),bid_order_price_0,float(self._quote[symbol]['asks'][0][0])))
                                    if abs(volume) >= (abs(_log_df['floor_change_volume'][symbol])/buy_resting_order_limit_level) :
                                        #实际挂单量算法,10分之一的总调仓量
                                        bid_order_volume_0 = math.floor((abs(_log_df['floor_change_volume'][symbol])/buy_resting_order_limit_level)*(10**init_precision[symbol]['vol'])+0.1)/(10**init_precision[symbol]['vol'])
                                    else :
                                        #实际挂单量算法,2分之一的当前调仓量,也就是小于总调仓量5%
                                        bid_order_volume_0 = math.floor((abs(volume)/2)*(10**init_precision[symbol]['vol'])+0.1)/(10**init_precision[symbol]['vol'])
                        elif (float(bids_list[0][0])/now_close-1 <= 0.01) and (float(bids_list[0][0])/now_close-1 > 0.005) and ((m_timestamp-self._start_timestamp > 180)) : 

                            self.logger.info('-----------2-1.盘中买入卖单追单-大于1倍速率-%s,%s-------------' %(m_timestamp,self._sell_after_order_timestamp))
                            #第1次追单
                            _open_orders = self._after_single_module(m_timestamp, 1, '','sell')
                            #第2次追单,判断成功取消订单量大于0
                            if (_open_orders) and len(_open_orders[0]) > 0 :
                                sleep(2)
                                _open_orders = self._after_single_module(m_timestamp, 2, '','sell')

                            bid_order_price_0 = math.floor((now_close*(1+c.BUY_AFTER_ORDER_LIMIT_RATIO))*(10**init_precision[symbol]['price'])+0.1)/(10**init_precision[symbol]['price']) 
                            bid_order_volume_0 = math.floor((0.6*abs(_log_df['floor_change_volume'][symbol])-abs(_log_df['realtime_change_volume'][symbol]))*(10**init_precision[symbol]['vol'])+0.1)/(10**init_precision[symbol]['vol'])
                            self.logger.info('--------------买单成交速率大于1--当前下单时间一半交易时间内--大于180秒--距离close价格千5以外,追单到币种交易量的百分之60--提升成交速率-symbol,bid_order_price_0,bid_order_volume_0-%s,%s,%s' %(symbol,bid_order_price_0,bid_order_volume_0))
                        elif (float(bids_list[0][0])/now_close-1 <= 0.01) and (float(bids_list[0][0])/now_close-1 > 0.005) and ((m_timestamp-self._start_timestamp <= 180)) : 

                            self.logger.info('-----------2-1.盘中买入卖单追单-大于1倍速率-%s,%s-------------' %(m_timestamp,self._sell_after_order_timestamp))
                            #第1次追单
                            _open_orders = self._after_single_module(m_timestamp, 1, '','sell')
                            #第2次追单,判断成功取消订单量大于0
                            if (_open_orders) and len(_open_orders[0]) > 0 :
                                sleep(2)
                                _open_orders = self._after_single_module(m_timestamp, 2, '','sell')

                            bid_order_price_0 = math.floor((now_close*(1+c.BUY_AFTER_ORDER_LIMIT_RATIO))*(10**init_precision[symbol]['price'])+0.1)/(10**init_precision[symbol]['price']) 
                            bid_order_volume_0 = math.floor((0.7*abs(_log_df['floor_change_volume'][symbol])-abs(_log_df['realtime_change_volume'][symbol]))*(10**init_precision[symbol]['vol'])+0.1)/(10**init_precision[symbol]['vol'])
                            self.logger.info('--------------买单成交速率大于1--当前下单时间一半交易时间内--小于180秒--距离close价格千5以外,追单到币种交易量的百分之70--提升成交速率-symbol,bid_order_price_0,bid_order_volume_0-%s,%s,%s' %(symbol,bid_order_price_0,bid_order_volume_0))
                        elif (float(bids_list[0][0])/now_close-1 > 0.01) and ((m_timestamp-self._start_timestamp > 180)) : 

                            self.logger.info('-----------2-1.盘中买入卖单追单-大于1倍速率-%s,%s-------------' %(m_timestamp,self._sell_after_order_timestamp))
                            #第1次追单
                            _open_orders = self._after_single_module(m_timestamp, 1, '','sell')
                            #第2次追单,判断成功取消订单量大于0
                            if (_open_orders) and len(_open_orders[0]) > 0 :
                                sleep(2)
                                _open_orders = self._after_single_module(m_timestamp, 2, '','sell')

                            bid_order_price_0 = math.floor((now_close*(1+c.BUY_AFTER_ORDER_LIMIT_RATIO))*(10**init_precision[symbol]['price'])+0.1)/(10**init_precision[symbol]['price']) 
                            bid_order_volume_0 = math.floor((0.8*abs(_log_df['floor_change_volume'][symbol])-abs(_log_df['realtime_change_volume'][symbol]))*(10**init_precision[symbol]['vol'])+0.1)/(10**init_precision[symbol]['vol'])
                            self.logger.info('--------------买单成交速率大于1--当前下单时间一半交易时间内--大于180秒--距离close价格百分之1以外,追单到币种交易量的百分之80--提升成交速率-symbol,bid_order_price_0,bid_order_volume_0-%s,%s,%s' %(symbol,bid_order_price_0,bid_order_volume_0))
                        elif (float(bids_list[0][0])/now_close-1 > 0.01) and ((m_timestamp-self._start_timestamp <= 180)) : 

                            self.logger.info('-----------2-1.盘中买入卖单追单-大于1倍速率-%s,%s-------------' %(m_timestamp,self._sell_after_order_timestamp))
                            #第1次追单
                            _open_orders = self._after_single_module(m_timestamp, 1, '','sell')
                            #第2次追单,判断成功取消订单量大于0
                            if (_open_orders) and len(_open_orders[0]) > 0 :
                                sleep(2)
                                _open_orders = self._after_single_module(m_timestamp, 2, '','sell')

                            bid_order_price_0 = math.floor((now_close*(1+c.BUY_AFTER_ORDER_LIMIT_RATIO))*(10**init_precision[symbol]['price'])+0.1)/(10**init_precision[symbol]['price']) 
                            bid_order_volume_0 = math.floor((1*abs(_log_df['floor_change_volume'][symbol])-abs(_log_df['realtime_change_volume'][symbol]))*(10**init_precision[symbol]['vol'])+0.1)/(10**init_precision[symbol]['vol'])
                            self.logger.info('--------------买单成交速率大于1--当前下单时间一半交易时间内--小于180秒--距离close价格百分之1以外,追单到币种交易量的百分之100--提升成交速率-symbol,bid_order_price_0,bid_order_volume_0-%s,%s,%s' %(symbol,bid_order_price_0,bid_order_volume_0))
                    #判断成交速率0.25,追单到速率0.5,速率1,速率2,币种交易量的50%,%60,%80
                    elif ('realtime_change_volume' in _log_df) and (symbol in _log_df['realtime_change_volume']) and ('floor_change_volume' in _log_df) and (symbol in _log_df['floor_change_volume']) and (abs(_log_df['realtime_change_volume'][symbol]/(m_timestamp-self._start_timestamp))/abs(_log_df['floor_change_volume'][symbol]/(self._cancel_order_timestamp-self._start_timestamp)) < 1) : 
                        self.logger.info('买单成交速率--当前下单时间一半交易时间内--小于1倍--对手价价格追单--提高成交速率-symbol,实时已成交量,需成交量,每秒已成交量,每秒需成交量,每秒已成交量/每秒需成交量-%s,%s,%s,%s,%s,%s' %(symbol,_log_df['realtime_change_volume'][symbol],_log_df['floor_change_volume'][symbol],(_log_df['realtime_change_volume'][symbol]/(m_timestamp-self._start_timestamp)),(_log_df['floor_change_volume'][symbol]/(self._cancel_order_timestamp-self._start_timestamp)),abs(_log_df['realtime_change_volume'][symbol]/(m_timestamp-self._start_timestamp))/abs(_log_df['floor_change_volume'][symbol]/(self._cancel_order_timestamp-self._start_timestamp))))
                        #如果距离close价格万5以内,close价格以下挂单
                        if (float(bids_list[0][0])/now_close-1 <= 0.0005) : 
                            self.logger.info('买单成交速率--当前下单时间一半交易时间内--小于1倍-距离close价格万5以内--对手价+1个单位进行挂单--提高成交速率-symbol,实时已成交量,需成交量,每秒已成交量,每秒需成交量,每秒已成交量/每秒需成交量-%s,%s,%s,%s,%s,%s' %(symbol,_log_df['realtime_change_volume'][symbol],_log_df['floor_change_volume'][symbol],(_log_df['realtime_change_volume'][symbol]/(m_timestamp-self._start_timestamp)),(_log_df['floor_change_volume'][symbol]/(self._cancel_order_timestamp-self._start_timestamp)),abs(_log_df['realtime_change_volume'][symbol]/(m_timestamp-self._start_timestamp))/abs(_log_df['floor_change_volume'][symbol]/(self._cancel_order_timestamp-self._start_timestamp))))
                            if (self._quote[symbol]['bids']) and (self._quote[symbol]['asks']) :
                                #买1档之之下下单价格:卖1档-一个单位价格
                                bid_order_price_0 = math.floor(float(self._quote[symbol]['asks'][0][0])*(10**init_precision[symbol]['price'])-0.9)/(10**init_precision[symbol]['price']) 
                                #如果下单价格小于卖1档且大于买1档进行下单
                                if (bid_order_price_0 > float(self._quote[symbol]['bids'][0][0])) and (bid_order_price_0 < float(self._quote[symbol]['asks'][0][0])) :
                                    self.logger.info('如果下单价格小于卖1档且大于买1档进行下单float(self._quote[symbol][bids][0][0]),bid_order_price_0,float(self._quote[symbol][asks][0][0]),-%s,%s,%s' %(float(self._quote[symbol]['bids'][0][0]),bid_order_price_0,float(self._quote[symbol]['asks'][0][0])))
                                    if abs(volume) >= (abs(_log_df['floor_change_volume'][symbol])/buy_resting_order_limit_level) :
                                        #实际挂单量算法,10分之一的总调仓量
                                        bid_order_volume_0 = math.floor((abs(_log_df['floor_change_volume'][symbol])/buy_resting_order_limit_level)*(10**init_precision[symbol]['vol'])+0.1)/(10**init_precision[symbol]['vol'])
                                    else :
                                        #实际挂单量算法,2分之一的当前调仓量,也就是小于总调仓量5%
                                        bid_order_volume_0 = math.floor((abs(volume)/2)*(10**init_precision[symbol]['vol'])+0.1)/(10**init_precision[symbol]['vol'])
                        #如果距离close价格千1以内,追单到速率1
                        elif (float(bids_list[0][0])/now_close-1 > 0.0005) and (float(bids_list[0][0])/now_close-1 <= 0.001) : 
                            bid_order_price_0 = math.floor((now_close*(1+c.BUY_AFTER_ORDER_LIMIT_RATIO))*(10**init_precision[symbol]['price'])+0.1)/(10**init_precision[symbol]['price']) 
                            bid_order_volume_0 = math.floor((1*abs(_log_df['floor_change_volume'][symbol])*(m_timestamp-self._start_timestamp)/(self._cancel_order_timestamp-self._start_timestamp)-abs(_log_df['realtime_change_volume'][symbol]))*(10**init_precision[symbol]['vol'])+0.1)/(10**init_precision[symbol]['vol'])
                            self.logger.info('--------------买单成交速率小于1--当前下单时间一半交易时间内--距离close价格千1以内,追单到速率1--提升成交速率-symbol,bid_order_price_0,bid_order_volume_0-%s,%s,%s' %(symbol,bid_order_price_0,bid_order_volume_0))
                        #如果距离close价格千2以内,追单到速率2
                        elif (float(bids_list[0][0])/now_close-1 > 0.001) and (float(bids_list[0][0])/now_close-1 <= 0.002) :
                            bid_order_price_0 = math.floor((now_close*(1+c.BUY_AFTER_ORDER_LIMIT_RATIO))*(10**init_precision[symbol]['price'])+0.1)/(10**init_precision[symbol]['price']) 
                            bid_order_volume_0 = math.floor((2*abs(_log_df['floor_change_volume'][symbol])*(m_timestamp-self._start_timestamp)/(self._cancel_order_timestamp-self._start_timestamp)-abs(_log_df['realtime_change_volume'][symbol]))*(10**init_precision[symbol]['vol'])+0.1)/(10**init_precision[symbol]['vol'])
                            self.logger.info('--------------买单成交速率小于1--当前下单时间一半交易时间内--距离close价格千2以内,追单到速率2--提升成交速率-symbol,bid_order_price_0,bid_order_volume_0-%s,%s,%s' %(symbol,bid_order_price_0,bid_order_volume_0))
                        #如果距离close价格千3以内,追单到币种交易量的50%
                        elif (float(bids_list[0][0])/now_close-1 > 0.002) and (float(bids_list[0][0])/now_close-1 <= 0.003) :
                            bid_order_price_0 = math.floor((now_close*(1+c.BUY_AFTER_ORDER_LIMIT_RATIO))*(10**init_precision[symbol]['price'])+0.1)/(10**init_precision[symbol]['price']) 
                            bid_order_volume_0 = math.floor((0.5*abs(_log_df['floor_change_volume'][symbol])-abs(_log_df['realtime_change_volume'][symbol]))*(10**init_precision[symbol]['vol'])+0.1)/(10**init_precision[symbol]['vol'])
                            self.logger.info('--------------买单成交速率小于1--当前下单时间一半交易时间内--距离close价格千3以内,追单到速率2--提升成交速率-symbol,bid_order_price_0,bid_order_volume_0-%s,%s,%s' %(symbol,bid_order_price_0,bid_order_volume_0))
                        #如果距离close价格千4以内,追单到币种交易量的60%
                        elif (float(bids_list[0][0])/now_close-1 > 0.003) and (float(bids_list[0][0])/now_close-1 <= 0.004) :
                            bid_order_price_0 = math.floor((now_close*(1+c.BUY_AFTER_ORDER_LIMIT_RATIO))*(10**init_precision[symbol]['price'])+0.1)/(10**init_precision[symbol]['price']) 
                            bid_order_volume_0 = math.floor((0.6*abs(_log_df['floor_change_volume'][symbol])-abs(_log_df['realtime_change_volume'][symbol]))*(10**init_precision[symbol]['vol'])+0.1)/(10**init_precision[symbol]['vol'])
                            self.logger.info('--------------买单成交速率小于1--当前下单时间一半交易时间内--距离close价格千4以内,追单到币种交易量的百分之50--提升成交速率-symbol,bid_order_price_0,bid_order_volume_0-%s,%s,%s' %(symbol,bid_order_price_0,bid_order_volume_0))
                        #如果距离close价格千5以内,追单到币种交易量的70%
                        elif (float(bids_list[0][0])/now_close-1 > 0.004) and (float(bids_list[0][0])/now_close-1 <= 0.005) :
                            bid_order_price_0 = math.floor((now_close*(1+c.BUY_AFTER_ORDER_LIMIT_RATIO))*(10**init_precision[symbol]['price'])+0.1)/(10**init_precision[symbol]['price']) 
                            bid_order_volume_0 = math.floor((0.7*abs(_log_df['floor_change_volume'][symbol])-abs(_log_df['realtime_change_volume'][symbol]))*(10**init_precision[symbol]['vol'])+0.1)/(10**init_precision[symbol]['vol'])
                            self.logger.info('--------------买单成交速率小于1--当前下单时间一半交易时间内--距离close价格千5以内,追单到币种交易量的百分之60--提升成交速率-symbol,bid_order_price_0,bid_order_volume_0-%s,%s,%s' %(symbol,bid_order_price_0,bid_order_volume_0))
                        #如果距离close价格千5以外,追单到币种交易量的80%
                        elif (float(bids_list[0][0])/now_close-1 > 0.005) :
                            self.logger.info('-----------2-1.盘中买入卖单追单-小于1倍速率-%s,%s-------------' %(m_timestamp,self._sell_after_order_timestamp))
                            #第1次追单
                            _open_orders = self._after_single_module(m_timestamp, 1, '','sell')
                            #第2次追单,判断成功取消订单量大于0
                            if (_open_orders) and len(_open_orders[0]) > 0 :
                                sleep(2)
                                _open_orders = self._after_single_module(m_timestamp, 2, '','sell')
                            bid_order_price_0 = math.floor((now_close*(1+c.BUY_AFTER_ORDER_LIMIT_RATIO))*(10**init_precision[symbol]['price'])+0.1)/(10**init_precision[symbol]['price']) 
                            bid_order_volume_0 = math.floor((0.8*abs(_log_df['floor_change_volume'][symbol])-abs(_log_df['realtime_change_volume'][symbol]))*(10**init_precision[symbol]['vol'])+0.1)/(10**init_precision[symbol]['vol'])
                            self.logger.info('--------------买单成交速率小于1--当前下单时间一半交易时间内--距离close价格小千5以外,追单到币种交易量的百分之80--提升成交速率-symbol,bid_order_price_0,bid_order_volume_0-%s,%s,%s' %(symbol,bid_order_price_0,bid_order_volume_0))
                #大于总成交的一半时间,开始提升成交速率
                elif ((m_timestamp-self._start_timestamp) > (self._cancel_order_timestamp-self._start_timestamp)/2):
                    #判断成交速率小于1.2,追单到速率1,速率2,币种交易量的50%,%60,70%,%80,90%,100%
                    if ('realtime_change_volume' in _log_df) and (symbol in _log_df['realtime_change_volume']) and ('floor_change_volume' in _log_df) and (symbol in _log_df['floor_change_volume']) and (abs(_log_df['realtime_change_volume'][symbol]/(m_timestamp-self._start_timestamp))/abs(_log_df['floor_change_volume'][symbol]/(self._cancel_order_timestamp-self._start_timestamp)) >= 1.2) : 
                        self.logger.info('买单成交速率--超过一半交易时间内--大于1.2倍--close价格以上挂单--降低成本-symbol,实时已成交量,需成交量,每秒已成交量,每秒需成交量,每秒已成交量/每秒需成交量,振幅-%s,%s,%s,%s,%s,%s,%s' %(symbol,_log_df['realtime_change_volume'][symbol],_log_df['floor_change_volume'][symbol],(_log_df['realtime_change_volume'][symbol]/(m_timestamp-self._start_timestamp)),(_log_df['floor_change_volume'][symbol]/(self._cancel_order_timestamp-self._start_timestamp)),abs(_log_df['realtime_change_volume'][symbol]/(m_timestamp-self._start_timestamp))/abs(_log_df['floor_change_volume'][symbol]/(self._cancel_order_timestamp-self._start_timestamp)),(float(bids_list[0][0])/now_close-1)))
                        #如果距离close价格万5以内,close价格以下挂单
                        if (float(bids_list[0][0])/now_close-1 <= 0.0005) : 
                            buy_resting_order_limit_ratio = 0 
                    #判断成交速率小于1.2,追单到速率1,速率2,币种交易量的50%,%60,70%,%80,90%,100%
                    elif ('realtime_change_volume' in _log_df) and (symbol in _log_df['realtime_change_volume']) and ('floor_change_volume' in _log_df) and (symbol in _log_df['floor_change_volume']) and (abs(_log_df['realtime_change_volume'][symbol]/(m_timestamp-self._start_timestamp))/abs(_log_df['floor_change_volume'][symbol]/(self._cancel_order_timestamp-self._start_timestamp)) < 1.2) : 
                        self.logger.info('买单成交速率--超过一半交易时间--小于1.2倍--对手价价格追单--提高成交速率-symbol,实时已成交量,需成交量,每秒已成交量,每秒需成交量,每秒已成交量/每秒需成交量-%s,%s,%s,%s,%s,%s' %(symbol,_log_df['realtime_change_volume'][symbol],_log_df['floor_change_volume'][symbol],(_log_df['realtime_change_volume'][symbol]/(m_timestamp-self._start_timestamp)),(_log_df['floor_change_volume'][symbol]/(self._cancel_order_timestamp-self._start_timestamp)),abs(_log_df['realtime_change_volume'][symbol]/(m_timestamp-self._start_timestamp))/abs(_log_df['floor_change_volume'][symbol]/(self._cancel_order_timestamp-self._start_timestamp))))
                        #如果距离close价格万5以内,close价格以下挂单
                        if (float(bids_list[0][0])/now_close-1 <= 0.0005) : 
                            self.logger.info('买单成交速率--超过一半交易时间--小于1.2倍-距离close价格万5以内--对手价+1个单位进行挂单--提高成交速率-symbol,实时已成交量,需成交量,每秒已成交量,每秒需成交量,每秒已成交量/每秒需成交量-%s,%s,%s,%s,%s,%s' %(symbol,_log_df['realtime_change_volume'][symbol],_log_df['floor_change_volume'][symbol],(_log_df['realtime_change_volume'][symbol]/(m_timestamp-self._start_timestamp)),(_log_df['floor_change_volume'][symbol]/(self._cancel_order_timestamp-self._start_timestamp)),abs(_log_df['realtime_change_volume'][symbol]/(m_timestamp-self._start_timestamp))/abs(_log_df['floor_change_volume'][symbol]/(self._cancel_order_timestamp-self._start_timestamp))))
                            if (self._quote[symbol]['bids']) and (self._quote[symbol]['asks']) :
                                #买1档之之下下单价格:卖1档-一个单位价格
                                bid_order_price_0 = math.floor(float(self._quote[symbol]['asks'][0][0])*(10**init_precision[symbol]['price'])-0.9)/(10**init_precision[symbol]['price']) 
                                #如果下单价格小于卖1档且大于买1档进行下单
                                if (bid_order_price_0 > float(self._quote[symbol]['bids'][0][0])) and (bid_order_price_0 < float(self._quote[symbol]['asks'][0][0])) :
                                    self.logger.info('如果下单价格小于卖1档且大于买1档进行下单float(self._quote[symbol][bids][0][0]),bid_order_price_0,float(self._quote[symbol][asks][0][0]),-%s,%s,%s' %(float(self._quote[symbol]['bids'][0][0]),bid_order_price_0,float(self._quote[symbol]['asks'][0][0])))
                                    if abs(volume) >= (abs(_log_df['floor_change_volume'][symbol])/buy_resting_order_limit_level) :
                                        #实际挂单量算法,10分之一的总调仓量
                                        bid_order_volume_0 = math.floor((abs(_log_df['floor_change_volume'][symbol])/buy_resting_order_limit_level)*(10**init_precision[symbol]['vol'])+0.1)/(10**init_precision[symbol]['vol'])
                                    else :
                                        #实际挂单量算法,当前调仓量
                                        bid_order_volume_0 = math.floor(abs(volume)*(10**init_precision[symbol]['vol'])+0.1)/(10**init_precision[symbol]['vol'])
                        #如果距离close价格千1以内,追单到币种交易量的55%
                        elif (float(bids_list[0][0])/now_close-1 > 0.0005) and (float(bids_list[0][0])/now_close-1 <= 0.001) : 
                            bid_order_price_0 = math.floor((now_close*(1+c.BUY_AFTER_ORDER_LIMIT_RATIO))*(10**init_precision[symbol]['price'])+0.1)/(10**init_precision[symbol]['price']) 
                            bid_order_volume_0 = math.floor((0.55*abs(_log_df['floor_change_volume'][symbol])-abs(_log_df['realtime_change_volume'][symbol]))*(10**init_precision[symbol]['vol'])+0.1)/(10**init_precision[symbol]['vol'])
                            self.logger.info('--------------买单成交速率--超过一半交易时间--距离close价格千1以内,追单到币种交易量的百分之55--提升成交速率-symbol,bid_order_price_0,bid_order_volume_0-%s,%s,%s' %(symbol,bid_order_price_0,bid_order_volume_0))
                        #如果距离close价格千2以内,追单到币种交易量的60%
                        elif (float(bids_list[0][0])/now_close-1 > 0.001) and (float(bids_list[0][0])/now_close-1 <= 0.002) :
                            bid_order_price_0 = math.floor((now_close*(1+c.BUY_AFTER_ORDER_LIMIT_RATIO))*(10**init_precision[symbol]['price'])+0.1)/(10**init_precision[symbol]['price']) 
                            bid_order_volume_0 = math.floor((0.6*abs(_log_df['floor_change_volume'][symbol])-abs(_log_df['realtime_change_volume'][symbol]))*(10**init_precision[symbol]['vol'])+0.1)/(10**init_precision[symbol]['vol'])
                            self.logger.info('--------------买单成交速率--超过一半交易时间--距离close价格千2以内,追单到币种交易量的百分之60--提升成交速率-symbol,bid_order_price_0,bid_order_volume_0-%s,%s,%s' %(symbol,bid_order_price_0,bid_order_volume_0))
                        #如果距离close价格千3以内,追单到币种交易量的70%
                        elif (float(bids_list[0][0])/now_close-1 > 0.002) and (float(bids_list[0][0])/now_close-1 <= 0.003) :
                            bid_order_price_0 = math.floor((now_close*(1+c.BUY_AFTER_ORDER_LIMIT_RATIO))*(10**init_precision[symbol]['price'])+0.1)/(10**init_precision[symbol]['price']) 
                            bid_order_volume_0 = math.floor((0.7*abs(_log_df['floor_change_volume'][symbol])-abs(_log_df['realtime_change_volume'][symbol]))*(10**init_precision[symbol]['vol'])+0.1)/(10**init_precision[symbol]['vol'])
                            self.logger.info('--------------买单成交速率--超过一半交易时间--距离close价格千3以内,追单到币种交易量的百分之70--提升成交速率-symbol,bid_order_price_0,bid_order_volume_0-%s,%s,%s' %(symbol,bid_order_price_0,bid_order_volume_0))
                        #如果距离close价格千4以内,追单到币种交易量的80%
                        elif (float(bids_list[0][0])/now_close-1 > 0.003) and (float(bids_list[0][0])/now_close-1 <= 0.004) :
                            bid_order_price_0 = math.floor((now_close*(1+c.BUY_AFTER_ORDER_LIMIT_RATIO))*(10**init_precision[symbol]['price'])+0.1)/(10**init_precision[symbol]['price']) 
                            bid_order_volume_0 = math.floor((0.8*abs(_log_df['floor_change_volume'][symbol])-abs(_log_df['realtime_change_volume'][symbol]))*(10**init_precision[symbol]['vol'])+0.1)/(10**init_precision[symbol]['vol'])
                            self.logger.info('--------------买单成交速率--超过一半交易时间--距离close价格千4以内,追单到币种交易量的百分之80--提升成交速率-symbol,bid_order_price_0,bid_order_volume_0-%s,%s,%s' %(symbol,bid_order_price_0,bid_order_volume_0))
                        #如果距离close价格千5以内,追单到币种交易量的90%
                        elif (float(bids_list[0][0])/now_close-1 > 0.004) and (float(bids_list[0][0])/now_close-1 <= 0.005) :
                            self.logger.info('-----------2-1.盘中买入卖单追单-超过一半交易时间-小于1倍速率-%s,%s-------------' %(m_timestamp,self._sell_after_order_timestamp))
                            #第1次追单
                            _open_orders = self._after_single_module(m_timestamp, 1, '','sell')
                            #第2次追单,判断成功取消订单量大于0
                            if (_open_orders) and len(_open_orders[0]) > 0 :
                                sleep(2)
                                _open_orders = self._after_single_module(m_timestamp, 2, '','sell')
                            bid_order_price_0 = math.floor((now_close*(1+c.BUY_AFTER_ORDER_LIMIT_RATIO))*(10**init_precision[symbol]['price'])+0.1)/(10**init_precision[symbol]['price']) 
                            bid_order_volume_0 = math.floor((0.9*abs(_log_df['floor_change_volume'][symbol])-abs(_log_df['realtime_change_volume'][symbol]))*(10**init_precision[symbol]['vol'])+0.1)/(10**init_precision[symbol]['vol'])
                            self.logger.info('--------------买单成交速率--超过一半交易时间--距离close价格千5以内,追单到币种交易量的百分之90--提升成交速率-symbol,bid_order_price_0,bid_order_volume_0-%s,%s,%s' %(symbol,bid_order_price_0,bid_order_volume_0))
                        #如果距离close价格千5以外,追单到币种交易量的100%
                        elif (float(bids_list[0][0])/now_close-1 > 0.005) :
                            self.logger.info('-----------2-1.盘中买入卖单追单-超过一半交易时间-小于1倍速率-%s,%s-------------' %(m_timestamp,self._sell_after_order_timestamp))
                            #第1次追单
                            _open_orders = self._after_single_module(m_timestamp, 1, '','sell')
                            #第2次追单,判断成功取消订单量大于0
                            if (_open_orders) and len(_open_orders[0]) > 0 :
                                sleep(2)
                                _open_orders = self._after_single_module(m_timestamp, 2, '','sell')
                            bid_order_price_0 = math.floor((now_close*(1+c.BUY_AFTER_ORDER_LIMIT_RATIO))*(10**init_precision[symbol]['price'])+0.1)/(10**init_precision[symbol]['price']) 
                            bid_order_volume_0 = math.floor((1*abs(_log_df['floor_change_volume'][symbol])-abs(_log_df['realtime_change_volume'][symbol]))*(10**init_precision[symbol]['vol'])+0.1)/(10**init_precision[symbol]['vol'])
                            self.logger.info('--------------买单成交速率--超过一半交易时间--距离close价格千5以外,追单到币种交易量的百分之100--提升成交速率-symbol,bid_order_price_0,bid_order_volume_0-%s,%s,%s' %(symbol,bid_order_price_0,bid_order_volume_0))

                #如果当前交易量小于追单交易量,先卖出追单再买入追单 
                if abs(volume) < abs(bid_order_volume_0) : 
                    #实际挂单量算法,当前调仓量
                    bid_order_volume_0 = math.floor(abs(volume)*(10**init_precision[symbol]['vol'])+0.1)/(10**init_precision[symbol]['vol'])

                #判断volume是否大于最小值
                if abs(bid_order_volume_0) < float(init_precision[symbol]['min_vol']) :
                    bid_order_volume_0 = 0

                if bid_order_volume_0 != 0 :
                    self.logger.info('_resting_single-i,symbol,bidPrice,bidVolume,bidtotalVolume,bid_order_price,bid_order_volume: %s,%s,%s,%s,%s,%s,%s' % (0, symbol, bid_order_price_0, bid_order_volume_0, bid_order_volume_0, bid_order_price_0, bid_order_volume_0))

                    #下单 margin_trading	String	1 币币交易订单. 2 杠杆交易订单 order_type	String	0：普通委托 1：只做Maker（Post only） 2：全部成交或立即取消（FOK） 3：立即成交并取消剩余（IOC）
                    self._take_order(m_timestamp, order_type, order_side, symbol, bid_order_volume_0, 1, '', bid_order_price_0, '')
                    #_order_params.append({'client_oid': 'id'+str(m_timestamp)+'0', 'instrument_id': symbol, 'side': order_side, 'type': order_type, 'size': bid_order_volume_0, 'price': bid_order_price_0, 'margin_trading': 1})
                    volume -= bid_order_volume_0
                    
            elif (direction == 'back') :
                buy_resting_order_limit_ratio = float(bids_list[c.BUY_RESTING_ORDER_LIMIT_POSITION_BACK][0])/now_close-1

            self.logger.info('symbol,buy_resting_order_limit_ratio,bids_list[0][0],now_close: %s,%s,%s,%s' % (symbol, buy_resting_order_limit_ratio,float(bids_list[0][0]),now_close)) 

            #计算N档卖挂单的挂单总量
            #买N档下单总挂单量
            order_total_volume_n = 0
            n = 1
            for bid in bids_list:
                if n > buy_resting_order_limit_level :
                    break
                order_total_volume_n += float(bid[1])
                n = n+1

            i = 1
            j = 1
            for bid in bids_list :
                bid_order_price = math.floor(float(bid[0])*(10**init_precision[symbol]['price'])+0.1)/(10**init_precision[symbol]['price']) 
                #1.当前深度各价格挂单量+n档价格分之一的成交量
                if c.BUY_RESTING_ORDER_METHOD_ID == 1 :
                    #实际挂单量算法,当前价格深度挂单量+10分之一的成交量
                    bid_order_volume = math.floor((float(bid[1])+abs(volume)/buy_resting_order_limit_level)*(10**init_precision[symbol]['vol'])+0.1)/(10**init_precision[symbol]['vol'])
                #2.当前深度各价格挂单量比率
                elif c.BUY_RESTING_ORDER_METHOD_ID == 2 :
                    bid_order_volume = math.floor(((float(bid[1])/order_total_volume_n)*abs(volume))*(10**init_precision[symbol]['vol'])+0.1)/(10**init_precision[symbol]['vol'])
                #3.总调仓量的n档价格分之一的成交量
                elif c.BUY_RESTING_ORDER_METHOD_ID == 3 :
                    #实际挂单量算法,10分之一的总调仓量
                    bid_order_volume = math.floor((abs(_log_df['floor_change_volume'][symbol])/buy_resting_order_limit_level)*(10**init_precision[symbol]['vol'])+0.1)/(10**init_precision[symbol]['vol'])
                else :
                    #实际挂单量算法,当前价格深度挂单量+10分之一的成交量
                    bid_order_volume = math.floor((float(bid[1])+abs(volume)/buy_resting_order_limit_level)*(10**init_precision[symbol]['vol'])+0.1)/(10**init_precision[symbol]['vol'])

                #如果挂单量小于最小挂单量,则替换为0,不为最小挂单量下单
                if abs(bid_order_volume) < float(init_precision[symbol]['min_vol']):
                    bid_order_volume = float(init_precision[symbol]['min_vol'])

                bid_total_volume += float(bid[1])
                self.logger.info('_resting_single-i,symbol,bidPrice,bidVolume,bidtotalVolume: %s,%s,%s,%s,%s' % (i, symbol, float(bid[0]), float(bid[1]), bid_total_volume))
                #买单挂单-调节买单挂单价格位置,当前判断大于close报价按照买单深度报价交易量挂单,平均挂多少档sell_level
                if bid_order_price < now_close*(1+buy_resting_order_limit_ratio) :
                    order_total_volume += bid_order_volume 
                    
                    #如果买单第一挂单价格等于当前挂单最大值
                    #if (j == 1) and (symbol in self._order_realtime_price_volume) and (self._order_realtime_price_volume[symbol]) and (bid_order_price == max(self._order_realtime_price_volume[symbol])) :
                    #    self.logger.info('买单下单1档价格等于当前持仓最大价格卖单,不进行调仓-: %s,%s,%s' % (symbol, bid_order_price, max(self._order_realtime_price_volume[symbol])))
                    #    break

                    #深度报价交易量加和大于交易量绝对值时N-1档对手报价
                    if (order_total_volume + float(init_precision[symbol]['min_vol'])) >= abs(volume) :
                        if j == 1 :
                            self.logger.info('_take_order-j1-order_type, order_side, symbol, volume, bid_order_pirce, now_close: %s,%s,%s,%s,%s,%s' % (order_type, order_side, symbol, abs(volume), bid_order_price, now_close))
                            #判断volume是否大于最小值
                            if abs(volume) < float(init_precision[symbol]['min_vol']) :
                                volume = 0

                            if volume != 0 :
                                #下单
                                #self._take_order(m_timestamp, order_type, order_side, symbol, abs(volume), 1, '', bid_order_price, '')
                                _order_params.append({'client_oid': 'id'+str(m_timestamp)+str(i), 'instrument_id': symbol, 'side': order_side, 'type': order_type, 'size': abs(volume), 'price': bid_order_price, 'margin_trading': 1})
                            else :
                                order_result = {'client_oid': '', 'error_code': 'volume-0', 'error_message': 'volume-0', 'order_id': '', 'result': 'error'} 
                                #解析订单结果
                                self._orderResult(order_result, m_timestamp, abs(volume), symbol, order_type, order_side, bid_order_price)
                        else :
                            order_last_volume = math.floor((abs(volume)-order_total_volume+bid_order_volume)*(10**init_precision[symbol]['vol'])+0.1)/(10**init_precision[symbol]['vol']) 
                            self.logger.info('_take_order-jn-order_type, order_side, symbol, order_last_volume, bid_order_pirce, now_close: %s,%s,%s,%s,%s,%s' % (order_type, order_side, symbol, order_last_volume, bid_order_price, now_close))
                            #判断volume是否大于最小值
                            if abs(order_last_volume) < float(init_precision[symbol]['min_vol']) :
                                order_last_volume = 0

                            if order_last_volume != 0 :
                                #下单
                                #self._take_order(m_timestamp, order_type, order_side, symbol, order_last_volume, 1, '', bid_order_price, '')
                                _order_params.append({'client_oid': 'id'+str(m_timestamp)+str(i), 'instrument_id': symbol, 'side': order_side, 'type': order_type, 'size': order_last_volume, 'price': bid_order_price, 'margin_trading': 1})
                            else :
                                order_result = {'client_oid': '', 'error_code': 'volume-0', 'error_message': 'volume-0', 'order_id': '', 'result': 'error'} 
                                #解析订单结果
                                self._orderResult(order_result, m_timestamp, order_last_volume, symbol, order_type, order_side, bid_order_price)
                        break
                    else :
                        self.logger.info('_take_order-order_type, order_side, symbol, volume, bid_order_pirce, now_close: %s,%s,%s,%s,%s,%s' % (order_type, order_side, symbol, bid_order_volume, bid_order_price, now_close))
                        #判断volume是否大于最小值
                        if abs(bid_order_volume) < float(init_precision[symbol]['min_vol']) :
                            bid_order_volume = 0

                        if bid_order_volume != 0 :
                            #下单
                            #self._take_order(m_timestamp, order_type, order_side, symbol, bid_order_volume, 1, '', bid_order_price, '')
                            _order_params.append({'client_oid': 'id'+str(m_timestamp)+str(i), 'instrument_id': symbol, 'side': order_side, 'type': order_type, 'size': bid_order_volume, 'price': bid_order_price, 'margin_trading': 1})
                        else :
                            order_result = {'client_oid': '', 'error_code': 'volume-0', 'error_message': 'volume-0', 'order_id': '', 'result': 'error'} 
                            #解析订单结果
                            self._orderResult(order_result, m_timestamp, bid_order_volume, symbol, order_type, order_side, bid_order_price)
                    j = j+1
                i = i+1
            if _order_params :
                #批量下单
                self._take_orders(m_timestamp, _order_params)

    #下单函数:执行下单-如果下单大于可用余额33017-根据可用余额重新调整金额下单
    def _take_order(self, m_timestamp, order_type, order_side, symbol, volume, margin_trading, client_oid, order_price, funds) :
        #take_order(self, otype, side, instrument_id, size, margin_trading=1, client_oid='', price='', funds='', order_type = ''):
        #参数名	类型	是否必填	描述
        #client_oid	String	否	由您设置的订单ID来识别您的订单,类型为字母（大小写）+数字或者纯字母（大小写） ，1-32位字符
        #type	String	否	limit，market(默认是limit)
        #side	String	是	buy or sell
        #instrument_id	String	是	币对名称
        #order_type	String	否	参数填数字，0：普通委托（order type不填或填0都是普通委托） 1：只做Maker（Post only） 2：全部成交或立即取消（FOK） 3：立即成交并取消剩余（IOC）
        #margin_trading	byte	否	下单类型(当前为币币交易，请求值为1)
        #{"client_oid": "", "error_code": 0, "error_message": "", "order_id": "2637076023487488", "result": true}
        spotAPI = spot.SpotAPI(apiKey, apiSecret, passphrase, True)
        order_result = spotAPI.take_order(order_type, order_side, symbol, abs(volume), 1, '', order_price, '')

        #如果出现现金不足情况,获取当前现金以及修改建仓数量
        #{"client_oid": "", "error_code": 0, "error_message": "", "order_id": "2637746160013312", "result": true}
        #{'client_oid': '', 'error_code': 33017, 'error_message': 'Greater than the maximum available balance', 'order_id': '-1', 'result': False}
        if (order_result) and ('result' in order_result) and (order_result['result'] == False) :
            logger.info('order_result False: %s' % (order_result))
            #描述	                业务错误码	http状态码	场景
            #下单大于最大可用余额	     33017	       400	下单余额不足
            if ('error_code' in order_result) and (str(order_result['error_code']) == '33017') :
                quote_currency_balance = 0
                tmp_quote_currency_balance = 0
                if order_side == 'buy' : 
                    spotAPI = spot.SpotAPI(apiKey, apiSecret, passphrase, True)
                    balance_result = spotAPI.get_account_info()
                    if balance_result :
                        for val in balance_result :
                            if val['currency'] == quote_currency :
                                #available 可用于交易数量
                                quote_currency_balance = float(val['available'])

                        if quote_currency in self._position_detail :
                            tmp_quote_currency_balance = float(self._position_detail[quote_currency]['available'])

                        logger.info('获取当前账户资产成功!quote_currency_balance,tmp_quote_currency_balance: %s,%s' %(quote_currency_balance,tmp_quote_currency_balance))
                    else :
                        #参数名	类型	描述
                        #currency	String	币种
                        #balance	String	余额
                        #hold	String	冻结(不可用)
                        #available	String	可用于交易或资金划转的数量
                        #id	String	账户 id
                        if quote_currency in self._position_detail :
                            quote_currency_balance = float(self._position_detail[quote_currency]['available'])
                        logger.info('获取当前账户资产失败!tmp_quote_currency_balance %s,%s' % (balance_result,quote_currency_balance))

                    if quote_currency_balance != 0 :
                        order_volume = math.floor((quote_currency_balance/order_price)*(10**init_precision[symbol]['vol'])-1)/(10**init_precision[symbol]['vol'])
                elif order_side == 'sell' : 
                    spotAPI = spot.SpotAPI(apiKey, apiSecret, passphrase, True)
                    balance_result = spotAPI.get_account_info()
                    if balance_result :
                        for val in balance_result :
                            if val['currency']+'-'+quote_currency == symbol:
                                #available 可用于交易数量
                                quote_currency_balance = float(val['available'])

                        if symbol in self._position_detail :
                            tmp_quote_currency_balance = float(self._position_detail[symbol]['available'])

                        logger.info('获取当前账户资产成功!quote_currency_balance,tmp_quote_currency_balance: %s,%s' %(quote_currency_balance,tmp_quote_currency_balance))
                    else :
                        #参数名	类型	描述
                        #currency	String	币种
                        #balance	String	余额
                        #hold	String	冻结(不可用)
                        #available	String	可用于交易或资金划转的数量
                        #id	String	账户 id
                        if symbol in self._position_detail :
                            quote_currency_balance = float(self._position_detail[symbol]['available'])
                        logger.info('获取当前账户资产失败!tmp_quote_currency_balance %s,%s' % (balance_result,quote_currency_balance))

                    tmp_order_volume = 0
                    if quote_currency_balance != 0 :
                        tmp_order_volume = math.floor((quote_currency_balance)*(10**init_precision[symbol]['vol'])-1)/(10**init_precision[symbol]['vol'])
                        if abs(volume) > abs(tmp_order_volume) : 
                            order_volume = abs(tmp_order_volume)
                        else :
                            order_volume = abs(volume)
                    else :
                        order_volume = 0

                if order_volume > abs(volume) :
                    order_volume = abs(volume)
                self.logger.info('现金不足情况,获取当前现金以及修改建仓数量,quote_currency_balance, order_price, volume, order_volume: %s,%s,%s,%s' % (quote_currency_balance, order_price, volume, order_volume))

                #判断order_volume是否大于最小值
                if order_volume < float(init_precision[symbol]['min_vol']) :
                    order_volume = 0
                #判断order_volume是否大于当前持仓
                
                if order_volume != 0 :
                    #下单
                    self._take_order(m_timestamp, order_type, order_side, symbol, order_volume, 1, '', order_price, '')
                else :
                    order_result = {'client_oid': '', 'error_code': 'volume-0', 'error_message': 'volume-0', 'order_id': '', 'result': 'error'} 
                    #解析订单结果
                    self._orderResult(order_result, m_timestamp, order_volume, symbol, order_type, order_side, order_price)
            else :
                #解析订单结果
                self._orderResult(order_result, m_timestamp, volume, symbol, order_type, order_side, order_price)
        else :
            #解析订单结果
            self._orderResult(order_result, m_timestamp, volume, symbol, order_type, order_side, order_price)

    #批量下单函数:执行下单-如果下单大于可用余额33017-根据可用余额重新调整金额下单
    # 限价单
    #params = [
    #    {'client_oid': '', 'instrument_id': 'BTC-USDT', 'side': 'buy', 'type': 'limit', 'size': 0.001, 'price': '9001', 'margin_trading': 1},
    #    {'client_oid': '', 'instrument_id': 'BTC-USDT', 'side': 'buy', 'type': 'limit', 'size': 0.001, 'price': '9002', 'margin_trading': 1},
    #]
    #{'btc-usdt': [{'client_oid': '', 'error_code': '', 'error_message': '', 'order_id': '3435401574230016', 'result': True}, {'client_oid': '', 'error_code': '', 'error_message': '', 'order_id': '3435401574295552', 'result': True}]}
    def _take_orders(self, m_timestamp, params) :
        logger.info('params: %s' % (params))
        #take_order(self, otype, side, instrument_id, size, margin_trading=1, client_oid='', price='', funds='', order_type = ''):
        #参数名	类型	是否必填	描述
        #client_oid	String	否	由您设置的订单ID来识别您的订单,类型为字母（大小写）+数字或者纯字母（大小写） ，1-32位字符
        #type	String	否	limit，market(默认是limit)
        #side	String	是	buy or sell
        #instrument_id	String	是	币对名称
        #order_type	String	否	参数填数字，0：普通委托（order type不填或填0都是普通委托） 1：只做Maker（Post only） 2：全部成交或立即取消（FOK） 3：立即成交并取消剩余（IOC）
        #margin_trading	byte	否	下单类型(当前为币币交易，请求值为1)
        #{"client_oid": "", "error_code": 0, "error_message": "", "order_id": "2637076023487488", "result": true}
        order_result_list = {}
        if (len(params) <= 10) and (len(params) > 0) :
            spotAPI = spot.SpotAPI(apiKey, apiSecret, passphrase, True)
            order_result_list = spotAPI.take_orders(params)
            logger.info('order_result_list : %s' % (order_result_list))
        elif len(params) > 10 :
            spotAPI = spot.SpotAPI(apiKey, apiSecret, passphrase, True)
            order_result_list = spotAPI.take_orders(params[0:10])
            logger.info('order_result_list-取1前10个订单下单 : %s' % (order_result_list))


        #如果出现现金不足情况,获取当前现金以及修改建仓数量
        #{"client_oid": "", "error_code": 0, "error_message": "", "order_id": "2637746160013312", "result": true}
        #{'client_oid': '', 'error_code': 33017, 'error_message': 'Greater than the maximum available balance', 'order_id': '-1', 'result': False}
        #params = [
        #    {'client_oid': '', 'instrument_id': 'BTC-USDT', 'side': 'buy', 'type': 'limit', 'size': 0.001, 'price': '9001', 'margin_trading': 1},
        #    {'client_oid': '', 'instrument_id': 'BTC-USDT', 'side': 'buy', 'type': 'limit', 'size': 0.001, 'price': '9002', 'margin_trading': 1},
        #]
        #order_result_list : {'btc-usdt': [{'client_oid': '', 'error_code': '33015', 'error_message': 'Batch operations exceed the maximum number limit', 'order_id': '-1', 'result': False}]}
        #order_result False: {'client_oid': '', 'error_code': '33015', 'error_message': 'Batch operations exceed the maximum number limit', 'order_id': '-1', 'result': False}
        if (order_result_list) :
            for symbol_l in order_result_list :
                symbol = symbol_l.upper()
                for order_result in order_result_list[symbol_l] :
                    client_oid = order_result['client_oid'] 
                    for params_list in params :
                        if (params_list['client_oid'] != '') and (params_list['client_oid'] == client_oid) :
                            order_type = params_list['type']
                            order_side = params_list['side']
                            volume = params_list['size']
                            order_price = params_list['price'] 

                    if ('result' in order_result) and (order_result['result'] == False) :
                        logger.info('order_result False: %s' % (order_result))

                        #描述	                业务错误码	http状态码	场景
                        #下单大于最大可用余额	     33017	       400	下单余额不足
                        if ('error_code' in order_result) and (str(order_result['error_code']) == '33017') :
                            quote_currency_balance = 0
                            tmp_quote_currency_balance = 0
                            if order_side == 'buy' : 
                                spotAPI = spot.SpotAPI(apiKey, apiSecret, passphrase, True)
                                balance_result = spotAPI.get_account_info()
                                if balance_result :
                                    for val in balance_result :
                                        if val['currency'] == quote_currency :
                                            #available 可用于交易数量
                                            quote_currency_balance = float(val['available'])

                                    if quote_currency in self._position_detail :
                                        tmp_quote_currency_balance = float(self._position_detail[quote_currency]['available'])

                                    logger.info('获取当前账户资产成功!quote_currency_balance,tmp_quote_currency_balance: %s,%s' %(quote_currency_balance,tmp_quote_currency_balance))
                                else :
                                    #参数名	类型	描述
                                    #currency	String	币种
                                    #balance	String	余额
                                    #hold	String	冻结(不可用)
                                    #available	String	可用于交易或资金划转的数量
                                    #id	String	账户 id
                                    if quote_currency in self._position_detail :
                                        quote_currency_balance = float(self._position_detail[quote_currency]['available'])
                                    logger.info('获取当前账户资产失败!tmp_quote_currency_balance %s,%s' % (balance_result,quote_currency_balance))

                                if quote_currency_balance != 0 :
                                    order_volume = math.floor((quote_currency_balance/order_price)*(10**init_precision[symbol]['vol'])-1)/(10**init_precision[symbol]['vol'])
                            elif order_side == 'sell' : 
                                spotAPI = spot.SpotAPI(apiKey, apiSecret, passphrase, True)
                                balance_result = spotAPI.get_account_info()
                                if balance_result :
                                    for val in balance_result :
                                        if val['currency']+'-'+quote_currency == symbol:
                                            #available 可用于交易数量
                                            quote_currency_balance = float(val['available'])

                                    if symbol in self._position_detail :
                                        tmp_quote_currency_balance = float(self._position_detail[symbol]['available'])

                                    logger.info('获取当前账户资产成功!quote_currency_balance,tmp_quote_currency_balance: %s,%s' %(quote_currency_balance,tmp_quote_currency_balance))
                                else :
                                    #参数名	类型	描述
                                    #currency	String	币种
                                    #balance	String	余额
                                    #hold	String	冻结(不可用)
                                    #available	String	可用于交易或资金划转的数量
                                    #id	String	账户 id
                                    if symbol in self._position_detail :
                                        quote_currency_balance = float(self._position_detail[symbol]['available'])
                                    logger.info('获取当前账户资产失败!tmp_quote_currency_balance %s,%s' % (balance_result,quote_currency_balance))

                                tmp_order_volume = 0
                                if quote_currency_balance != 0 :
                                    tmp_order_volume = math.floor((quote_currency_balance)*(10**init_precision[symbol]['vol'])-1)/(10**init_precision[symbol]['vol'])
                                    if abs(volume) > abs(tmp_order_volume) : 
                                        order_volume = abs(tmp_order_volume)
                                    else :
                                        order_volume = abs(volume)
                                else :
                                    order_volume = 0

                            if order_volume > abs(volume) :
                                order_volume = abs(volume)
                            self.logger.info('现金不足情况,获取当前现金以及修改建仓数量,quote_currency_balance, order_price, volume, order_volume: %s,%s,%s,%s' % (quote_currency_balance, order_price, volume, order_volume))

                            #判断order_volume是否大于最小值
                            if order_volume < float(init_precision[symbol]['min_vol']) :
                                order_volume = 0
                            #判断order_volume是否大于当前持仓
                
                            if order_volume != 0 :
                                #下单
                                self._take_order(m_timestamp, order_type, order_side, symbol, order_volume, 1, '', order_price, '')
                            else :
                                order_result = {'client_oid': '', 'error_code': 'volume-0', 'error_message': 'volume-0', 'order_id': '', 'result': 'error'} 
                                #解析订单结果
                                self._orderResult(order_result, m_timestamp, order_volume, symbol, order_type, order_side, order_price)
                        else :
                            #解析订单结果
                            self._orderResult(order_result, m_timestamp, volume, symbol, order_type, order_side, order_price)
                    else :
                        #解析订单结果
                        self._orderResult(order_result, m_timestamp, volume, symbol, order_type, order_side, order_price)

    #解析订单结果函数:解析下单返回信息-记录下单信息到order字典
    def _orderResult(self, order_result, m_timestamp, volume, symbol, order_type, order_side, now_close) :
        #{"client_oid": "", "error_code": 0, "error_message": "", "order_id": "2637746160013312", "result": true}
        m_datetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(m_timestamp))
        self.logger.info('order_result: %s' % (order_result))
        #订单-submitted-已提交
        order_id = 0
        if (order_result) and ('result' in order_result) and (order_result['result'] == True) and ('order_id' in order_result):
            order_state = 'submit'
            order_key = int(order_result['order_id'])
            order_id = int(order_result['order_id'])
        #订单-error-min-错误-买卖最小金额限制
        elif (order_result) and ('result' in order_result) and (order_result['result'] == 'error') and ('error_code' in order_result) and (order_result['error_code'] == 'order-limitorder-amount-min-error') :
            self.logger.debug('huobi-order error-min: %s' % (order_result))
            order_state = 'error-min'
            order_key = order_state 
        #订单-error-insufficient-错误-没有足够基础货币购买
        elif (order_result) and ('result' in order_result) and (order_result['result'] == 'error') and ('error_code' in order_result) and (order_result['error_code'] == 'account-frozen-balance-insufficient-error') :
            self.logger.debug('huobi-order error-insufficient: %s' % (order_result))
            order_state = 'error-insufficient'
            order_key = order_state 
        #交易量为0
        elif (order_result) and ('result' in order_result) and (order_result['result'] == 'error') and ('error_code' in order_result) and (order_result['error_code'] == 'volume-0') :
            order_state = 'volume-0'
            order_key = order_state 
        #订单-error-other-错误-其他
        else :
            order_state = 'error-other'
            order_key = order_state 
            self.logger.info('order error-other: %s' % (order_result))

        self.logger.info('$$$order$$$,%s,%s,%s,%s,%s,%s,%s' % (m_datetime, symbol, order_type, order_side, volume, now_close, order_state))

        #{'table': 'spot/order', 'data': [{'client_oid': '', 'filled_notional': '0', 'filled_size': '0', 'instrument_id': 'BTC-USDT', 'last_fill_px': '0', 'last_fill_qty': '0', 'last_fill_time': '1970-01-01T00:00:00.000Z', 'margin_trading': '1', 'notional': '', 'order_id': '2660873117969408', 'order_type': '0', 'price': '5115.7', 'side': 'sell', 'size': '0.01580547', 'status': 'open', 'timestamp': '2019-04-15T14:15:02.000Z', 'type': 'limit'}]}
        #{'table': 'spot/order', 'data': [{'client_oid': '', 'filled_notional': '80.856042879', 'filled_size': '0.01580547', 'instrument_id': 'BTC-USDT', 'last_fill_px': '5115.7', 'last_fill_qty': '0.00410949', 'last_fill_time': '2019-04-15T14:15:01.913Z', 'margin_trading': '1', 'notional': '', 'order_id': '2660873117969408', 'order_type': '0', 'price': '5115.7', 'side': 'sell', 'size': '0.01580547', 'status': 'filled', 'timestamp': '2019-04-15T14:15:02.000Z', 'type': 'limit'}]}
        # 参数名	类型	描述
        #order_id	long	订单ID
        #client_oid	String	由用户设置的订单ID
        #price	        String	价格
        #size	        String	交易货币数量
        #notional	String	买入金额，市价买入时返回
        #instrument_id	String	币对名称
        #side	        String	buy or sell
        #type	        String	limit,market(默认是limit)
        #timestamp	String	订单创建时间
        #filled_size	String	已成交数量
        #filled_notional	String	已成交金额
        #status	        String	订单状态( open:未成交 part_filled:部分成交 filled:已成交 cancelled:已撤销 failure:订单失败 )
        #margin_trading	String	1 币币交易订单. 2 杠杆交易订单
        #order_type	String	0：普通委托 1：只做Maker（Post only） 2：全部成交或立即取消（FOK） 3：立即成交并取消剩余（IOC）
        #last_fill_px	String	最新成交价格 （如果没有，推0）
        #last_fill_qty	String	最新成交数量（如果没有，推0）
        #last_fill_time	String	最新成交时间（如果没有，推1970-01-01T00:00:00.000Z）

        order_tmp = {}
        order_tmp = {'client_oid': '', 'filled_notional': '0', 'filled_size': '0', 'instrument_id': symbol, 'last_fill_px': '0', 'last_fill_qty': '0', 'last_fill_time': '1970-01-01T00:00:00.000Z', 'margin_trading': '1', 'notional': '', 'order_id': order_id, 'order_type': '0', 'price': now_close, 'side': order_side, 'size': volume, 'status': order_state, 'timestamp': m_datetime, 'type': order_type}
        if symbol in self._order :
            if order_key in self._order[symbol] :
                self._order[symbol][order_key].update({order_state:order_tmp})
            else :
                self._order[symbol].update({order_key:{order_state:order_tmp}})
        else: 
            self._order.update({symbol:{order_key:{order_state:order_tmp}}})

        if (order_result) and ('result' in order_result) and (order_result['result'] == True) and ('order_id' in order_result):
            #submit状态更新realtime_open_nofilled_volume数据
            self._realtime_order_volume()

    #根据下单成功的submit状态-实时更新下单量,避免websocket回报丢失造成重复下单
    def _realtime_order_volume(self) : 
        self._order_realtime_price_volume = {}
        for (symbol,order_values) in list(self._order.items()) :
            if symbol not in symbol_list : continue 
            #实时已成交量
            _log_df.at[symbol,'realtime_change_volume'] = 0.0
            #实时未成交量
            _log_df.at[symbol,'realtime_nofilled_volume'] = 0.0
            #实时下单未成交量
            _log_df.at[symbol,'realtime_open_nofilled_volume'] = 0.0
            #实时未下单
            _log_df.at[symbol,'realtime_noopen_volume'] = 0.0
            #实时已成交close滑点成本
            _log_df.at[symbol,'realtime_filled_cost'] = 0.0
            #实时未成交close滑点成本
            _log_df.at[symbol,'realtime_nofilled_cost'] = 0.0
            #实时成交比率
            _log_df.at[symbol,'realtime_filled_ratio'] = 0.0
            #实时成交速率
            _log_df.at[symbol,'realtime_filled_rate'] = 0.0
            #实时成交比率
            _log_df.at[symbol,'realtime_filled_ratio'] = 0.0
            #实时成交速率
            _log_df.at[symbol,'realtime_filled_rate'] = 0.0

            #成交速率和成交比率
            if ((self._order_timestamp-self._start_timestamp) > 0) and ((self._cancel_order_timestamp-self._start_timestamp) > 0) and (abs(_log_df['floor_change_volume'][symbol]) > 0) and ('realtime_change_volume' in _log_df) and (symbol in _log_df['realtime_change_volume']) and ('floor_change_volume' in _log_df) and (symbol in _log_df['floor_change_volume']) :
                _log_df.at[symbol,'realtime_filled_rate'] = abs(_log_df['realtime_change_volume'][symbol]/(self._order_timestamp-self._start_timestamp))/abs(_log_df['floor_change_volume'][symbol]/(self._cancel_order_timestamp-self._start_timestamp)) 
                _log_df.at[symbol,'realtime_filled_ratio'] = abs(_log_df['realtime_change_volume'][symbol])/abs(_log_df['floor_change_volume'][symbol])

            #if ('realtime_change_volume' in _log_df) and (symbol in _log_df['realtime_change_volume']) and ('floor_change_volume' in _log_df) and (symbol in _log_df['floor_change_volume']) and (abs(_log_df['realtime_change_volume'][symbol]/(m_timestamp-self._start_timestamp))/abs(_log_df['floor_change_volume'][symbol]/(self._cancel_order_timestamp-self._start_timestamp)) > 3): 
            for (order_id,order_value) in list(order_values.items()) :
                #临时-实时下单未成交量
                _log_df.at[symbol,'tmp_realtime_open_nofilled_volume'] = 0.0
                #临时-实时已成交量
                _log_df.at[symbol,'tmp_realtime_change_volume'] = 0.0
                #临时-实时close滑点成本
                _log_df.at[symbol,'tmp_realtime_filled_cost'] = 0.0
                for (order_type,order_info) in list(order_value.items()) :
                    #下单
                    if (order_type == 'submit') or (order_type == 'open') :
                        if ('side' in order_info) and (order_info['side'] == 'sell') :
                            _log_df.at[symbol, 'tmp_realtime_open_nofilled_volume'] = -float(order_info['size'])

                            #实时下单价格和交易量
                            if (symbol in self._order_realtime_price_volume) :
                                if (symbol in self._order_realtime_price_volume) and (float(order_info['price']) in self._order_realtime_price_volume[symbol]) :
                                    if (symbol in self._order_realtime_price_volume) and (float(order_info['price']) in self._order_realtime_price_volume[symbol]) and (not int(order_info['order_id']) in self._order_realtime_price_volume[symbol][float(order_info['price'])]) : 
                                        self._order_realtime_price_volume[symbol][float(order_info['price'])].update({int(order_info['order_id']):-float(order_info['size'])})
                                else :
                                    self._order_realtime_price_volume[symbol].update({float(order_info['price']):{int(order_info['order_id']):-float(order_info['size'])}})
                            else :
                                self._order_realtime_price_volume.update({symbol:{float(order_info['price']):{int(order_info['order_id']):-float(order_info['size'])}}})
                        elif ('side' in order_info) and (order_info['side'] == 'buy') : 
                            _log_df.at[symbol, 'tmp_realtime_open_nofilled_volume'] = float(order_info['size'])

                            #实时下单价格和交易量
                            if (symbol in self._order_realtime_price_volume) :
                                if (symbol in self._order_realtime_price_volume) and (float(order_info['price']) in self._order_realtime_price_volume[symbol]) :
                                    if (symbol in self._order_realtime_price_volume) and (float(order_info['price']) in self._order_realtime_price_volume[symbol]) and (not int(order_info['order_id']) in self._order_realtime_price_volume[symbol][float(order_info['price'])]) : 
                                        self._order_realtime_price_volume[symbol][float(order_info['price'])].update({int(order_info['order_id']):float(order_info['size'])})
                                else :
                                    self._order_realtime_price_volume[symbol].update({float(order_info['price']):{int(order_info['order_id']):float(order_info['size'])}})
                            else :
                                self._order_realtime_price_volume.update({symbol:{float(order_info['price']):{int(order_info['order_id']):float(order_info['size'])}}})
                        else :
                            logger.info('realtime open-nofilled-amount not sell-limit and not buy-limit')

                    #取消订单
                    #{'client_oid': '', 'created_at': '2019-07-22T15:45:21.220Z', 'filled_notional': '30.6793656', 'filled_size': '1078.74', 'funds': '', 'instrument_id': 'TRX-USDT', 'notional': '', 'order_id': '3216134714497024', 'order_type': '0', 'price': '0.02844', 'price_avg': '0.02844', 'product_id': 'TRX-USDT', 'side': 'sell', 'size': '1472.67', 'state': '-1', 'status': 'cancelled', 'timestamp': '2019-07-22T15:45:21.220Z', 'type': 'limit'}
                    elif (order_type == 'cancelled') or (order_type == 'failure'):
                        '''
                        if ('side' in order_info) and (order_info['side'] == 'sell') :
                            _log_df.at[symbol, 'tmp_realtime_change_volume'] = -float(order_info['filled_size'])
                        elif ('side' in order_info) and (order_info['side'] == 'buy') : 
                            _log_df.at[symbol, 'tmp_realtime_change_volume'] = float(order_info['filled_size'])
                        else :
                            logger.info('realtime cancelled-nofilled-amount not sell-limit and not buy-limit')
                        '''
                        #取消状态-开仓未成交为0
                        _log_df.at[symbol,'tmp_realtime_open_nofilled_volume'] = 0.0

                        #实时下单价格和交易量
                        if (symbol in self._order_realtime_price_volume) and (float(order_info['price']) in self._order_realtime_price_volume[symbol]) and (int(order_info['order_id']) in self._order_realtime_price_volume[symbol][float(order_info['price'])]) :
                            del(self._order_realtime_price_volume[symbol][float(order_info['price'])][int(order_info['order_id'])])
                            if (symbol in self._order_realtime_price_volume) and (float(order_info['price']) in self._order_realtime_price_volume[symbol]) and (len(self._order_realtime_price_volume[symbol][float(order_info['price'])]) == 0) :
                                del(self._order_realtime_price_volume[symbol][float(order_info['price'])])

                    #部分成交
                    elif (order_type != 'filled') and ('part_filled' in order_type) : 
                        if ('side' in order_info) and (order_info['side'] == 'sell') :
                            _log_df.at[symbol, 'tmp_realtime_open_nofilled_volume'] = float(order_info['filled_size'])-float(order_info['size'])
                            _log_df.at[symbol, 'tmp_realtime_change_volume'] = -float(order_info['filled_size'])
                            _log_df.at[symbol, 'tmp_realtime_filled_cost'] += float(order_info['filled_notional'])-(_log_df.at[symbol, 'now_close']*float(order_info['filled_size']))
                        elif ('side' in order_info) and (order_info['side'] == 'buy') : 
                            _log_df.at[symbol, 'tmp_realtime_open_nofilled_volume'] = float(order_info['size'])-float(order_info['filled_size'])
                            _log_df.at[symbol, 'tmp_realtime_change_volume'] = float(order_info['filled_size'])
                            _log_df.at[symbol, 'tmp_realtime_filled_cost'] += (_log_df.at[symbol, 'now_close']*float(order_info['filled_size']))-float(order_info['filled_notional'])
                        else :
                            logger.info('realtime part_filled-nofilled-amount not sell-limit and not buy-limit')
                    #完全成交
                    elif order_type == 'filled' : 
                        #filled in filled和part_filled
                        #按照成交顺序订阅更新单一订单的已成交数量和已成交金额，filled_size已成交数量,filled_notional已成交金额
                        if ('side' in order_info) and (order_info['side'] == 'sell') :
                            _log_df.at[symbol, 'tmp_realtime_change_volume'] = -float(order_info['filled_size'])
                            _log_df.at[symbol, 'tmp_realtime_filled_cost'] = float(order_info['filled_notional'])-(_log_df.at[symbol, 'now_close']*float(order_info['size']))
                        elif ('side' in order_info) and (order_info['side'] == 'buy') : 
                            _log_df.at[symbol, 'tmp_realtime_change_volume'] = float(order_info['filled_size'])
                            _log_df.at[symbol, 'tmp_realtime_filled_cost'] = (_log_df.at[symbol, 'now_close']*float(order_info['size']))-float(order_info['filled_notional']) 
                        else :
                            logger.info('realtime filled-amount not sell-limit and not buy-limit')
                        #完全成交状态-开仓未成交为0
                        _log_df.at[symbol,'tmp_realtime_open_nofilled_volume'] = 0.0

                        #实时下单价格和交易量
                        if (symbol in self._order_realtime_price_volume) and (float(order_info['price']) in self._order_realtime_price_volume[symbol]) and (int(order_info['order_id']) in self._order_realtime_price_volume[symbol][float(order_info['price'])]) :
                            del(self._order_realtime_price_volume[symbol][float(order_info['price'])][int(order_info['order_id'])])
                            if (symbol in self._order_realtime_price_volume) and (float(order_info['price']) in self._order_realtime_price_volume[symbol]) and (len(self._order_realtime_price_volume[symbol][float(order_info['price'])]) == 0) :
                                del(self._order_realtime_price_volume[symbol][float(order_info['price'])])

                #实时下单未成交:同一币对多个订单的已成交数量和已成交金额加和
                _log_df.at[symbol, 'realtime_open_nofilled_volume'] += _log_df.at[symbol, 'tmp_realtime_open_nofilled_volume']
                #实时已成交量:同一币对多个订单的已成交数量和已成交金额加和
                _log_df.at[symbol, 'realtime_change_volume'] += _log_df.at[symbol, 'tmp_realtime_change_volume']
                #实时close滑点成本:同一币对多个订单的已成交数量和已成交金额加和
                _log_df.at[symbol, 'realtime_filled_cost'] += _log_df.at[symbol, 'tmp_realtime_filled_cost']

            #实时未成交量 = 需成交量-实时已成交量
            _log_df.at[symbol, 'realtime_nofilled_volume'] = _log_df.at[symbol, 'floor_change_volume'] - _log_df.at[symbol, 'realtime_change_volume']
            #取消这个判断,因为可能存在多下单情况无法反映,如果实时下单未成交大于需成交量,说明取消订单信息丢失
            #if abs(_log_df.at[symbol, 'realtime_nofilled_volume']) < abs(_log_df.at[symbol, 'realtime_open_nofilled_volume']) :
                #_log_df.at[symbol, 'realtime_open_nofilled_volume'] = _log_df.at[symbol, 'realtime_nofilled_volume'] 

            #实时未下单量 = 需成交量-实时已成交量-实时下单未成交量
            _log_df.at[symbol, 'realtime_noopen_volume'] = _log_df.at[symbol, 'floor_change_volume'] - _log_df.at[symbol, 'realtime_change_volume'] - _log_df.at[symbol, 'realtime_open_nofilled_volume']

            #实时-总close滑点成本
            #_log_df['realtime_total_cost'] = 0.0
            #实时-未成交close滑点成本
            #_log_df['realtime_nofilled_cost'] = 0.0

        self.logger.info('-----------实时未成交成本预估--------------')
        for i in list(range(len(_log_df['realtime_nofilled_volume']))) : 
            symbol = _log_df['realtime_nofilled_volume'].index[i]
            if symbol not in symbol_list : continue 
            volume = _log_df.realtime_nofilled_volume[symbol] 
            #不等于usdt,选出调仓量小于0的卖单处理
            if (symbol != quote_currency) :
                #临时-实时未成交close滑点成本预估 
                _log_df.at[symbol,'realtime_nofilled_cost'] = 0.0
                #卖单追单成本估算
                if (_log_df.floor_change_volume[symbol] < 0) and (abs(_log_df.realtime_nofilled_volume[symbol]) > float(init_precision[symbol]['min_vol'])) and (symbol in self._quote) and ('bids' in self._quote[symbol]) and (len(self._quote[symbol]['bids']) >= 10) :
                    self.logger.debug('_resting_single-leng(bids): %s,%s' % (symbol,len(self._quote[symbol]['bids'])))

                    #买报价价格
                    bid_order_price = 0
                    #买报价挂单量
                    bid_order_volume = 0
                    #买下单总挂单量
                    order_total_volume = 0
                    #买下单最后挂单量
                    order_last_volume = 0
                    n = 1
                    for bid in self._quote[symbol]['bids']:
                        bid_order_price = math.floor(float(bid[0])*(10**init_precision[symbol]['price'])+0.1)/(10**init_precision[symbol]['price']) 
                        bid_order_volume = math.floor(float(bid[1])*(10**init_precision[symbol]['vol'])+0.1)/(10**init_precision[symbol]['vol'])
                        #如果挂单量小于最小挂单量,则替换为0,不为最小挂单量下单
                        if abs(bid_order_volume) < float(init_precision[symbol]['min_vol']):
                            bid_order_volume = float(init_precision[symbol]['min_vol'])

                        order_total_volume += bid_order_volume 
                        self.logger.info('_resting_single-i,symbol,bidPrice,bidVolume,bidtotalVolume: %s,%s,%s,%s,%s' % (n, symbol, float(bid[0]), float(bid[1]), order_total_volume))

                        #深度报价交易量加和大于交易量绝对值时N-1档对手报价
                        if (order_total_volume + float(init_precision[symbol]['min_vol'])) >= abs(volume) :
                            if n == 1 :
                                #判断volume是否大于最小值
                                if abs(volume) < float(init_precision[symbol]['min_vol']) :
                                    volume = 0

                                if volume != 0 :
                                    _log_df.at[symbol,'realtime_nofilled_cost'] += (_log_df.realtime_now_close[symbol]-bid_order_price)*volume 
                            else :
                                order_last_volume = math.floor((abs(volume)-order_total_volume+bid_order_volume)*(10**init_precision[symbol]['vol'])+0.1)/(10**init_precision[symbol]['vol']) 
                                #判断volume是否大于最小值
                                if abs(order_last_volume) < float(init_precision[symbol]['min_vol']) :
                                    order_last_volume = 0

                                if order_last_volume != 0 :
                                    _log_df.at[symbol,'realtime_nofilled_cost'] += (_log_df.realtime_now_close[symbol]-bid_order_price)*order_last_volume
                            break
                        else :
                            #判断volume是否大于最小值
                            if abs(bid_order_volume) < float(init_precision[symbol]['min_vol']) :
                                bid_order_volume = 0

                            if bid_order_volume != 0 :
                                _log_df.at[symbol,'realtime_nofilled_cost'] += (_log_df.realtime_now_close[symbol]-bid_order_price)*bid_order_volume
                        n = n+1
                #买单追单成本估算
                elif (_log_df.floor_change_volume[symbol] > 0) and (abs(_log_df.realtime_nofilled_volume[symbol]) > float(init_precision[symbol]['min_vol'])) and (symbol in self._quote) and ('asks' in self._quote[symbol]) and (len(self._quote[symbol]['asks']) >= 10) :
                    self.logger.debug('_resting_single-leng(asks): %s,%s' % (symbol,len(self._quote[symbol]['asks'])))

                    #买报价价格
                    ask_order_price = 0
                    #买报价挂单量
                    ask_order_volume = 0
                    #买下单总挂单量
                    order_total_volume = 0
                    #买下单最后挂单量
                    order_last_volume = 0
                    n = 1
                    for ask in self._quote[symbol]['asks']:
                        ask_order_price = math.floor(float(ask[0])*(10**init_precision[symbol]['price'])+0.1)/(10**init_precision[symbol]['price']) 
                        ask_order_volume = math.floor(float(ask[1])*(10**init_precision[symbol]['vol'])+0.1)/(10**init_precision[symbol]['vol'])
                        #如果挂单量小于最小挂单量,则替换为0,不为最小挂单量下单
                        if abs(ask_order_volume) < float(init_precision[symbol]['min_vol']):
                            ask_order_volume = float(init_precision[symbol]['min_vol'])

                        order_total_volume += ask_order_volume 
                        self.logger.info('_resting_single-i,symbol,askPrice,askVolume,asktotalVolume: %s,%s,%s,%s,%s' % (n, symbol, float(ask[0]), float(ask[1]), order_total_volume))

                        #深度报价交易量加和大于交易量绝对值时N-1档对手报价
                        if (order_total_volume + float(init_precision[symbol]['min_vol'])) >= abs(volume) :
                            if n == 1 :
                                #判断volume是否大于最小值
                                if abs(volume) < float(init_precision[symbol]['min_vol']) :
                                    volume = 0

                                if volume != 0 :
                                    _log_df.at[symbol,'realtime_nofilled_cost'] += (_log_df.realtime_now_close[symbol]-ask_order_price)*volume 
                            else :
                                order_last_volume = math.floor((abs(volume)-order_total_volume+ask_order_volume)*(10**init_precision[symbol]['vol'])+0.1)/(10**init_precision[symbol]['vol']) 
                                #判断volume是否大于最小值
                                if abs(order_last_volume) < float(init_precision[symbol]['min_vol']) :
                                    order_last_volume = 0

                                if order_last_volume != 0 :
                                    _log_df.at[symbol,'realtime_nofilled_cost'] += (_log_df.realtime_now_close[symbol]-ask_order_price)*order_last_volume
                            break
                        else :
                            #判断volume是否大于最小值
                            if abs(ask_order_volume) < float(init_precision[symbol]['min_vol']) :
                                ask_order_volume = 0

                            if ask_order_volume != 0 :
                                _log_df.at[symbol,'realtime_nofilled_cost'] += (_log_df.realtime_now_close[symbol]-ask_order_price)*ask_order_volume
                        n = n+1
                #实时总成本 = 实时已成交close滑点成本-实时未成交close滑点成本
                _log_df.at[symbol, 'realtime_total_cost'] = _log_df.at[symbol, 'realtime_filled_cost'] + _log_df.at[symbol, 'realtime_nofilled_cost']

    #数据处理模块
    def _get_trade_data(self, message):
        try:
            #sub trade,depth,order,account-订阅数据
            #{'event': 'subscribe', 'channel': 'spot/account:USDT'}
            if ('event' in message) and (message['event'] == 'subscribe') :
                self.logger.info("Subscribed to %s." % message['channel'])

            #pong-心跳数据
            elif ('pong' in message) :
                self.logger.debug("pong %s." % message)

            #auth-登陆数据 
            #{'event': 'login', 'success': True}
            elif ('event' in message) and (message['event'] == 'login') and ('success' in message) :
                if message['success'] == True:
                    self.logger.info("login: %s" %(message))

            #trade detail-交易数据
            #参数名	参数类型	描述
            #trade_id	String	成交id
            #price	String	成交价格
            #size	String	成交数量
            #side	String	成交方向（buy or sell）
            #timestamp	String	成交时间
            #instrument_id	String	币对
            #{"table": "spot/trade", "data": [{'instrument_id': 'BTC-USDT', 'price': '5133.1', 'side': 'sell', 'size': '0.02394361', 'timestamp': '2019-04-15T09:22:59.484Z', 'trade_id': '1315460352'}]}
            elif ('table' in message) and (message['table'] == 'spot/trade') and ('data' in message):
                #'insert'  - new row
                self.logger.debug('Tick-trade detail-insert:%s' % (message))
                for v in message['data']:
                    if ('instrument_id' in v) and ('timestamp' in v) :
                        m_symbol = v['instrument_id'] 
                        #判断每分钟开始时刻执行
                        m_datetime = v['timestamp'][0:10]+" "+v['timestamp'][11:17]+"00"

                        #时间处理-后一条信息时间如果小于前一条信息时间,则后一条消息时间等于前一条消息时间
                        if (self._trade_pre_time != '') and (m_datetime < self._trade_pre_time) :
                            self.logger.debug('Tick-trade detail-insert error data:%s-%s-%s' % (message, m_datetime, self._trade_pre_time))
                            m_datetime = self._trade_pre_time
                        
                        #判断最新消息分钟-上一消息分钟不等于0,为新的1分钟进行上一分钟合成
                        if (self._trade_pre_time != '') and (m_datetime >= self._trade_pre_time) and (int(m_datetime[14:16])-int(self._trade_pre_time[14:16]) != 0) and (int(m_datetime[14:16]) in list(range(0,60,1))) :
                            self.logger.info('M1 _nowtime - _pertime: %s - %s' % (m_datetime, self._trade_pre_time))
                            #将当前分钟交易数据存入数据字典,插值处理
                            for _symbol in symbol_list :
                                #如果tick合成最新分钟存在数据
                                if _symbol in self._trade_tmp : 
                                    self._trade[_symbol] = self._trade_tmp[_symbol]
                                    self._trade[_symbol]['datetime'] = self._trade_pre_time[0:10]+" "+self._trade_pre_time[11:17]+"00"
                                    self._pre_trade[_symbol] = self._trade[_symbol]
                                elif _symbol in self._pre_trade:
                                    #如果tick合成最新分钟不存在数据，取上一次合成数据close作为ohlc数据，volume等于0
                                    self._trade[_symbol] = self._pre_trade[_symbol]
                                    self._trade[_symbol]['datetime'] = self._trade_pre_time[0:10]+" "+self._trade_pre_time[11:17]+"00"
                                    self._trade[_symbol]['open'] = self._pre_trade[_symbol]['close'] 
                                    self._trade[_symbol]['high'] = self._pre_trade[_symbol]['close'] 
                                    self._trade[_symbol]['low'] = self._pre_trade[_symbol]['close'] 
                                    self._trade[_symbol]['vol'] = 0 

                            #清空tick合成1分钟暂存数据字典
                            self._trade_tmp.clear()

                            #当前时刻tick数据转换成分钟数据暂存
                            if m_symbol in self._trade_tmp :
                                self._trade_tmp[m_symbol] = self.tickToMinute(v,m_symbol)
                            else :
                                self._trade_tmp[m_symbol] = [] 
                                self._trade_tmp[m_symbol] = self.tickToMinute(v,m_symbol)

                            #处理1分钟实时和历史数据进行合并
                            if self._trade_mn and self._trade_m15:
                                #将最新的1分钟数据存入历史一分钟数据临时队列
                                for _symbol in self._trade :
                                    df_m1_last = pd.DataFrame.from_dict(self._trade[_symbol],orient='index').T
                                    df_m1_last.index = pd.to_datetime(df_m1_last.datetime)

                                    #存入45分钟临时1分钟队列
                                    if _symbol in self._trade_m1_tmp :
                                        self._trade_m1_tmp[_symbol] = df_m1_last.append(self._trade_m1_tmp[_symbol])
                                    else :
                                        self._trade_m1_tmp[_symbol] = pd.DataFrame()   
                                        self._trade_m1_tmp[_symbol] = df_m1_last.append(self._trade_m1_tmp[_symbol])

                                    #存入15分钟临时1分钟队列
                                    if _symbol in self._trade_m1_tmp_m15 :
                                        self._trade_m1_tmp_m15[_symbol] = df_m1_last.append(self._trade_m1_tmp_m15[_symbol])
                                    else :
                                        self._trade_m1_tmp_m15[_symbol] = pd.DataFrame()   
                                        self._trade_m1_tmp_m15[_symbol] = df_m1_last.append(self._trade_m1_tmp_m15[_symbol])

                                self.logger.info('now M1 tmp dict from :\r\n %s' % self._trade_m1_tmp[symbol_list[len(symbol_list)-1]].ix[:1])
                            else :
                                #获取历史数据:从实时数据合成第2根1分钟数据开始获取
                                if self._minute_num == 1 :
                                    #处理历史的时间窗口分钟和最新时间窗口分钟的1分钟数据
                                    self.getHistoryData(symbol_list)

                                    #将最新的1分钟数据存入历史一分钟数据队列
                                    for _symbol in self._trade :
                                        df_m1_last = pd.DataFrame.from_dict(self._trade[_symbol],orient='index').T
                                        df_m1_last.index = pd.to_datetime(df_m1_last.datetime)

                                        #存入45分钟临时1分钟队列
                                        if _symbol in self._trade_m1_tmp:
                                            self._trade_m1_tmp[_symbol] = df_m1_last.append(self._trade_m1_tmp[_symbol])
                                        else :
                                            self._trade_m1_tmp[_symbol] = pd.DataFrame()   
                                            self._trade_m1_tmp[_symbol] = df_m1_last.append(self._trade_m1_tmp[_symbol])

                                        #存入15分钟临时1分钟队列
                                        if _symbol in self._trade_m1_tmp :
                                            self._trade_m1_tmp_m15[_symbol] = df_m1_last.append(self._trade_m1_tmp_m15[_symbol])
                                        else :
                                            self._trade_m1_tmp_m15[_symbol] = pd.DataFrame()   
                                            self._trade_m1_tmp_m15[_symbol] = df_m1_last.append(self._trade_m1_tmp_m15[_symbol])
                                    self.logger.info('now M1 tmp dict from :\r\n %s' % self._trade_m1_tmp[symbol_list[len(symbol_list)-1]].ix[:1])

                            #处理窗口周期数据,增加self._trade_mn判断是过滤掉第一分钟未取历史数据情况
                            if ((int(m_datetime[11:13])*60+int(m_datetime[14:16]))%period_number) == 0 and ((int(m_datetime[11:13])*60+int(m_datetime[14:16]))%period_number) != ((int(self._trade_pre_time[11:13])*60+int(self._trade_pre_time[14:16]))%period_number) and self._trade_mn:
                                self.logger.info('M%s _nowtime - _pertime: %s - %s' % (period_number,m_datetime,self._trade_pre_time))
                                #合成最近n分钟数据
                                for _symbol in symbol_list :
                                    if _symbol in self._trade_m1_tmp and _symbol in self._trade_mn :
                                        df_m15_tmp = self.convMxtoMn(self._trade_m1_tmp[_symbol],window_period)
                                        self._trade_mn[_symbol] = self._trade_mn[_symbol].append(df_m15_tmp)
                                self.logger.info('now M%s dict from :\r\n %s' % (period_number,self._trade_mn[symbol_list[len(symbol_list)-1]]))
                                self._trade_m1_tmp.clear()

                            '''
                            ###########15分钟处理窗口周期数据,增加self._trade_mn判断是过滤掉第一分钟未取历史数据情况
                            if ((int(m_datetime[11:13])*60+int(m_datetime[14:16]))%period_number_15min) == 0 and ((int(m_datetime[11:13])*60+int(m_datetime[14:16]))%period_number_15min) != ((int(self._trade_pre_time[11:13])*60+int(self._trade_pre_time[14:16]))%period_number_15min) and self._trade_m15:
                                self.logger.info('M%s _nowtime - _pertime: %s - %s' % (period_number_15min, m_datetime, self._trade_pre_time))
                                #合成最近n分钟数据
                                for _symbol in symbol_list :
                                    if _symbol in self._trade_m1_tmp_m15 and _symbol in self._trade_m15 :
                                        df_m15_tmp = self.convMxtoMn(self._trade_m1_tmp_m15[_symbol],window_period_15min)
                                        self._trade_m15[_symbol] = self._trade_m15[_symbol].append(df_m15_tmp)
                                self.logger.info('now M%s dict from :\r\n %s' % (period_number_15min,self._trade_m15[symbol_list[len(symbol_list)-1]]))
                                self._trade_m1_tmp_m15.clear()
                            '''

                            self._minute_num += 1
                        else :
                            if m_symbol in self._trade_tmp :
                                self._trade_tmp[m_symbol] = self.tickToMinute(v,m_symbol)
                            else :
                                self._trade_tmp[m_symbol] = [] 
                                self._trade_tmp[m_symbol] = self.tickToMinute(v,m_symbol)
                        self._trade_pre_time = m_datetime 

            #depth step0-报价深度数据
            #参数名	参数类型	描述
            #price	String	价格
            #size	String	数量
            #timestamp	String	时间戳
            #num_orders	String	组成此条深度的订单数量
            #instrument_id	String	币对
            #checksum	String	检验和
            #["411.8","10",8][price ,size ,num_orders]
            #{'table': 'spot/depth', 'action': 'update', 'data': [{'instrument_id': 'LTC-USDT', 'asks': [['82.08', '88.799226', 4], ['82.11', '0.677', 1], ['82.13', '8.076', 3], ['82.14', '16.050318', 5], ['82.15', '67.495073', 8], ['82.16', '16.818211', 7], ['82.17', '16.420122', 6], ['82.2', '107.999859', 5], ['82.21', '0.57104', 3], ['82.25', '57.925016', 3], ['82.3', '90.258635', 5]], 'bids': [['82.05', '0.66', 1], ['82.01', '22.77656', 8], ['82', '52.793909', 11], ['81.99', '5.611773', 9], ['81.98', '33.03742', 22], ['81.97', '35.013163', 13], ['81.96', '58.14296', 15], ['81.95', '7.056106', 10], ['81.93', '115.95094', 12], ['81.91', '12.650235', 6], ['81.88', '11.570018', 9], ['81.87', '15.916077', 6], ['81.86', '39.694619', 2], ['81.85', '36.955308', 4]], 'timestamp': '2019-04-15T09:32:51.209Z', 'checksum': 1680391679}]}
            elif ('table' in message) and (message['table'] == 'spot/depth') and ('data' in message):
                self.logger.debug("bids-asks: %s" %(message))
                m_symbol = message['data'][0]['instrument_id']

                #局部全量数据 
                if ('action' in message) and (message['action'] == 'partial') :
                    self._quote[m_symbol] = {} 
                    self._quote[m_symbol] = {'bids':message['data'][0]['bids'],'asks':message['data'][0]['asks']} 
                    self._quote_tmp[m_symbol] = copy.deepcopy(self._quote[m_symbol])
                #增量数据
                elif ('action' in message) and (message['action'] == 'update') :
                    if m_symbol in self._quote:
                        self._quote_tmp[m_symbol] = copy.deepcopy(self._quote[m_symbol])
                        self.logger.debug("pre_bids-asks: %s" %(self._quote[m_symbol]))
                        #循环增量数据
                        for val_add in message['data'][0]['bids'] :
                            i = 0
                            j = 0
                            #循环当前全量数据
                            for val_all in self._quote[m_symbol]['bids'] :
                                #增量价格 > 全量bid价格,插入bid之前
                                if (float(val_add[0]) > float(val_all[0])) :
                                    self.logger.debug("bid_price_add>bid_price_all: %s-%s" %(val_add,val_all))
                                    self._quote[m_symbol]['bids'].insert(i,val_add)
                                    j = j+1
                                    break 
                                #增量价格 == 全量bid价格
                                elif (float(val_add[0]) == float(val_all[0])) :
                                    self.logger.debug("bid_price_add=bid_pirce_all: %s-%s" %(val_add,val_all))
                                    #数量 == 0,删掉全量此价格数据
                                    if float(val_add[1]) == 0 :
                                        self._quote[m_symbol]['bids'].remove(val_all)
                                    #数量 != 0,替换此价格数据
                                    else :
                                        self._quote[m_symbol]['bids'][i] = val_add
                                    j = j+1
                                    break 
                                i = i+1
                            if j == 0 :
                                self.logger.debug("bid_price_add<bidn_price_all: %s-%s" %(val_add,val_all))
                                self._quote[m_symbol]['bids'].insert(i,val_add)

                        for val_add in message['data'][0]['asks'] :
                            i = 0
                            j = 0
                            #循环当前全量数据
                            for val_all in self._quote[m_symbol]['asks'] :
                                #增量价格 < 全量ask价格,插入ask之前
                                if (float(val_add[0]) < float(val_all[0])) :
                                    self.logger.debug("ask_price_add<bid_price_all: %s-%s" %(val_add,val_all))
                                    self._quote[m_symbol]['asks'].insert(i,val_add)
                                    j = j+1
                                    break 
                                #增量价格 == 全量ask价格
                                elif (float(val_add[0]) == float(val_all[0])) :
                                    self.logger.debug("ask_price_add=ask_pirce_all: %s-%s" %(val_add,val_all))
                                    #数量 == 0,删掉全量此价格数据
                                    if float(val_add[1]) == 0 :
                                        self._quote[m_symbol]['asks'].remove(val_all)
                                    #数量 != 0,替换此价格数据
                                    else :
                                        self._quote[m_symbol]['asks'][i] = val_add
                                    j = j+1
                                    break 
                                i = i+1
                            if j == 0 :
                                self.logger.debug("ask_price_add>askn_price_all: %s-%s" %(val_add,val_all))
                                self._quote[m_symbol]['asks'].insert(i,val_add)
                    else :
                        self._quote[m_symbol] = {} 
                        self._quote[m_symbol] = {'bids':message['data'][0]['bids'],'asks':message['data'][0]['asks']} 
                        self._quote_tmp[m_symbol] = copy.deepcopy(self._quote[m_symbol])

                    self.logger.debug("modify self._quote[m_symbol]: %s" %(self._quote[m_symbol]))

                checksum = message['data'][0]['checksum']
                sum_bids_asks = ''
                for i in list(range(25)) :
                    if i == 0 :
                        sum_bids_asks = self._quote[m_symbol]['bids'][i][0]+":"+self._quote[m_symbol]['bids'][i][1]+":"+self._quote[m_symbol]['asks'][i][0]+":"+self._quote[m_symbol]['asks'][i][1]
                    else :
                        sum_bids_asks = sum_bids_asks+":"+self._quote[m_symbol]['bids'][i][0]+":"+self._quote[m_symbol]['bids'][i][1]+":"+self._quote[m_symbol]['asks'][i][0]+":"+self._quote[m_symbol]['asks'][i][1]
                checksum_diff = binascii.crc32(sum_bids_asks.encode())

                #会存在传递的checksum错误情况，因为修改后再次修改有可能正确
                if checksum != checksum_diff :
                    if checksum != ctypes.c_int32(checksum_diff).value :
                        self.logger.info("error sum_bids-sum_asks-checksum: %s-%s-%s-%s" %(m_symbol,sum_bids_asks,checksum,checksum_diff))
                        self.logger.debug("new self._quote[m_symbol]: %s-%s" %(m_symbol,self._quote[m_symbol]))
                        self.logger.debug("old self._quote[m_symbol]: %s-%s" %(m_symbol,self._quote_tmp[m_symbol]))
                    else :
                        self.logger.debug("python3-src32-sum_bids-sum_asks-checksum: %s-%s-%s-%s" %(m_symbol,sum_bids_asks,checksum,ctypes.c_int32(checksum_diff).value))
                else :
                    self.logger.debug("sum_bids-sum_asks-checksum: %s-%s-%s-%s" %(m_symbol,sum_bids_asks,checksum,checksum_diff))
                
                self.logger.debug("self._quote[m_symbol]-bids-asks: %s,%s" %(m_symbol, self._quote[m_symbol]))
            
            #公共-5档深度频道
            #返回参数
            #参数名	参数类型	描述
            #price	String	卖方深度
            #size	String	买方深度
            #timestamp	String	时间戳
            #num_orders	String	组成此条深度的订单数量
            #instrument_id	String	币对
            elif ('table' in message) and (message['table'] == 'spot/depth5') and ('data' in message):
                self.logger.debug("bids-asks: %s" %(message))
                m_symbol = message['data'][0]['instrument_id']
                if m_symbol in self._quote5:
                    self._quote5[m_symbol] = {'bids':message['data'][0]['bids'],'asks':message['data'][0]['asks']} 
                else :
                    self._quote5[m_symbol] = {} 
                    self._quote5[m_symbol] = {'bids':message['data'][0]['bids'],'asks':message['data'][0]['asks']} 
                #self.logger.info("self._quote5[m_symbol]-bids-asks: %s,%s" %(m_symbol, self._quote5[m_symbol]))

            #order-订单数据
            #参数名	类型	描述
            #order_id	String	订单ID
            #client_oid	String	由用户设置的订单ID
            #price	String	委托价格
            #size	String	委托数量（交易货币数量）
            #notional	String	买入金额，市价买入时返回
            #instrument_id	String	币对名称
            #side	String	buy or sell
            #type	String	limit,market(默认是limit)
            #timestamp	String	订单创建时间
            #filled_size	String	已成交数量
            #filled_notional	String	已成交金额
            #margin_trading	String	1 币币交易订单. 2 杠杆交易订单
            #order_type	String	0：普通委托 1：只做Maker（Post only） 2：全部成交或立即取消（FOK） 3：立即成交并取消剩余（IOC）
            #last_fill_px	String	最新成交价格 （如果没有，推0）
            #last_fill_qty	String	最新成交数量（如果没有，推0）
            #last_fill_time	String	最新成交时间（如果没有，推1970-01-01T00:00:00.000Z）
            #state	String	订单状态("-2":失败,"-1":撤单成功,"0":等待成交 ,"1":部分成交, "2":完全成交,"3":下单中,"4":撤单中,）
            #status为state旧版参数，会短期兼容，建议尽早切换state。
            #{'table': 'spot/order', 'data': [{'client_oid': '', 'filled_notional': '0', 'filled_size': '0', 'instrument_id': 'BTC-USDT', 'last_fill_px': '0', 'last_fill_qty': '0', 'last_fill_time': '1970-01-01T00:00:00.000Z', 'margin_trading': '1', 'notional': '', 'order_id': '2658394894578688', 'order_type': '0', 'price': '5132', 'side': 'buy', 'size': '0.00659918', 'status': 'open', 'timestamp': '2019-04-15T03:44:47.000Z', 'type': 'limit'}]}
            elif ('table' in message) and (message['table'] == 'spot/order') and ('data' in message):
                self.logger.info("Order: %s",message)
                #0-等待成交-open, 2-完全成交(终态)-filled, 1-部分成交-part_filled, -1-已撤销(终态)-cancelled ,-2-订单失败-failure 
                for v in message['data'] :
                    if (v) and ('instrument_id' in v) and ('order_id' in v) and ('status' in v) and ('timestamp' in v) :
                        #存储所有状态的订单信息
                        if v['instrument_id'] in self._order :
                            if int(v['order_id']) in self._order[v['instrument_id']] :
                                if (v['status'] in self._order[v['instrument_id']][int(v['order_id'])]) and (v['status'] != 'filled') :
                                    self._order[v['instrument_id']][int(v['order_id'])].update({(str(v['status'])+"_"+str(v['timestamp'])):v})
                                else :
                                    self._order[v['instrument_id']][int(v['order_id'])].update({v['status']:v})
                            else :
                                self._order[v['instrument_id']].update({int(v['order_id']):{v['status']:v}})
                        else: 
                            self._order.update({v['instrument_id']:{int(v['order_id']):{v['status']:v}}})

                    else :
                        self.logger.info("Order信息数据不全: %s" %(message))

                    self.logger.debug("self._order[v['instrument_id']]: %s-%s" %(v['instrument_id'],self._order[v['instrument_id']]))

                #实时信息需要使用self._order所以需要处理完成后使用
                #需成交量
                #_log_df.at[symbol, 'floor_change_volume']
                #实时下单未成交量
                #_log_df['realtime_open_nofilled_volume'] = 0.0 
                #实时已成交量
                #_log_df.at[symbol,'realtime_change_volume'] = 0.0
                #实时未成交量 = 需成交总量-实时已成交量
                #_log_df.at[symbol,'realtime_nofilled_volume'] = 0.0
                #实时未下单量 = 需成交总量-实时已成交量-实时下单未成交量
                #_log_df['realtime_noopen_volume'] = 0.0 
                for v in message['data'] :
                    if (v) and ('instrument_id' in v) and ('order_id' in v) and ('status' in v) and ('timestamp' in v) :
                        if ((v['status'] == 'open') or (v['status'] == 'cancelled') or (v['status'] == 'failure') or ('filled' in v['status'])) and ('floor_change_volume' in _log_df) and ('realtime_open_nofilled_volume' in _log_df) and ('realtime_change_volume' in _log_df) and ('realtime_nofilled_volume' in _log_df) and ('realtime_noopen_volume' in _log_df):
                            #实时更新各种状态订单交易量
                            self._realtime_order_volume()
                            if ((v['status'] == 'open') or (v['status'] == 'cancelled') or (v['status'] == 'failure') or ('filled' in v['status'])) : 
                                self.logger.info('realtime model detail:\r\n %s,%s,%s,%s,%s' % (_log_df[['realtime_filled_rate','realtime_filled_ratio','realtime_total_cost','realtime_nofilled_cost','realtime_filled_cost','realtime_now_close','realtime_output_change','floor_change_volume','realtime_change_volume','realtime_nofilled_volume','realtime_open_nofilled_volume','realtime_noopen_volume']].T,self._order_realtime_price_volume,_log_df.realtime_total_cost[1:].sum(),_log_df.realtime_nofilled_cost[1:].sum(),_log_df.realtime_filled_cost[1:].sum()))


            #Position-order.match-持仓数据
            #{'table': 'spot/account', 'data': [{'balance': '136.781211684', 'available': '102.914219924', 'currency': 'USDT', 'id': '9196334', 'hold': '33.86699176'}]}
            #{'table': 'spot/account', 'data': [{'balance': '183.770262803', 'available': '183.770262803', 'currency': 'USDT', 'id': '9196334', 'hold': '0'}]}
            #{'table': 'spot/account', 'data': [{'balance': '0.00013148474', 'available': '0.00013148474', 'currency': 'BTC', 'id': '9196334', 'hold': '0'}]}
            #参数名	类型	描述
            #currency	String	币种
            #balance	String	余额
            #hold	String	冻结(不可用)
            #available	String	可用于交易或资金划转的数量
            #id	String	账户 id
            elif ('table' in message) and (message['table'] == 'spot/account') and ('data' in message):
                self.logger.info("Position: %s" %(message))
                for v in message['data']:
                    #根据下单状态进行控制
                    #下单状态self._order_status:卖单挂单sell_resting_order,卖单追单sell_after_order,买单挂单buy_resting_order,买单追单buy_after_order,取消订单cancel_order
                    if (quote_currency in self._position_detail) and (float(self._position_detail[quote_currency]['available']) != 0) and (float(v['available']) > float(self._position_detail[quote_currency]['available'])) and (self._order_status == 'buy_resting_order') :
                        self.logger.info("Position_detail buy_resting_order: %s" %(self._position_detail[quote_currency]))

                    self._position[v['currency']] = v['balance'] 
                    self._position_detail[v['currency']] = {'balance':v['balance'],'available':v['available'],'hold':v['hold']}
                    self.logger.debug("Position: %s,%s" %(v['currency'],v['balance']))
            else :
                #{'event': 'error', 'message': 'Internal system error', 'errorCode': 30043}
                #{'event': 'error', 'message': 'User not logged in / User must be logged in', 'errorCode': 30041}
                self.logger.info("other: %s" %(message))
        except Exception as e:
            self.logger.error(traceback.format_exc())
            self.logger.error(e)

    def tickToMinute(self,v,symbol) :
        _v = {}
        _v['datetime'] = v['timestamp']
        _v['symbol'] = symbol 
        if 'open' in self._trade_tmp[symbol]: 
            _v['open'] = float(self._trade_tmp[symbol]['open'])
        else :
            _v['open'] = float(v['price'])
        if 'high' in self._trade_tmp[symbol]: 
            if float(v['price']) > self._trade_tmp[symbol]['high'] :
                _v['high'] = float(v['price']) 
            else :
                _v['high'] = self._trade_tmp[symbol]['high']
        else :
            _v['high'] = float(v['price'])
        if 'low' in self._trade_tmp[symbol] :
            if float(v['price']) < self._trade_tmp[symbol]['low'] and float(v['price']) > 0:
                _v['low'] = float(v['price']) 
            else :
                _v['low'] = self._trade_tmp[symbol]['low']
        else :
            _v['low'] = float(v['price'])
        _v['close'] = float(v['price']) 
        if 'vol' in self._trade_tmp[symbol]:
            _v['vol'] = self._trade_tmp[symbol]['vol']+float(v['size'])
        else :
            _v['vol'] = float(v['size'])
        return _v

    #获取历史数据
    def getHistoryData(self,symbol_list) :
        for symbol in symbol_list :
            try :
                #每次最多获取200条，所以取15分钟数据来组合45分钟
                spotAPI = spot.SpotAPI(apiKey, apiSecret, passphrase, True)
                rest = spotAPI.get_kline(symbol, '', '', 900)

                if (not rest) :
                    self.logger.info("spotAPI.get_kline(symbol, '', '', 900)-1: %s,%s" %(symbol,rest))
                    sleep(2)
                    spotAPI = spot.SpotAPI(apiKey, apiSecret, passphrase, True)
                    rest = spotAPI.get_kline(symbol, '', '', 900)
                    self.logger.info("spotAPI.get_kline(symbol, '', '', 900)-2: %s,%s" %(symbol,rest))
            except Exception as e:
                self.logger.error(traceback.format_exc())
                self.logger.error(e)
                sleep(2)
                spotAPI = spot.SpotAPI(apiKey, apiSecret, passphrase, True)
                rest = spotAPI.get_kline(symbol, '', '', 900)
                self.logger.info("spotAPI.get_kline(symbol, '', '', 900)-2: %s,%s" %(symbol,rest))

            df_m15_1 = pd.read_json(json.dumps(rest), orient='records')
            df_m15_1.columns = ['datetime','open','high','low','close','vol']
            df_m15_1['symbol'] = symbol
            df_m15_end = df_m15_1[-1:].datetime.values[0] 
            df_m15_start = (datetime.datetime.strptime(df_m15_end, "%Y-%m-%dT%H:%M:%S.%fZ") - datetime.timedelta(hours=50)).strftime("%Y-%m-%dT%H:%M:%S.%fZ") 
            df_m15_1['datetime'] = df_m15_1.datetime.str.replace('T',' ').str.replace('.000Z','') 
            df_m15_1.index = df_m15_1.datetime
            df_m15_1 = df_m15_1[self.OKEX_MBAR_HEADER]

            try :
                #每次最多获取200条，所以取15分钟数据来组合45分钟
                spotAPI = spot.SpotAPI(apiKey, apiSecret, passphrase, True)
                rest = spotAPI.get_kline(symbol, df_m15_start, df_m15_end, 900)

                if (not rest) :
                    self.logger.info("spotAPI.get_kline(symbol, df_m15_start, df_m15_end, 900)-1: %s,%s" %(symbol,rest))
                    sleep(2)
                    spotAPI = spot.SpotAPI(apiKey, apiSecret, passphrase, True)
                    rest = spotAPI.get_kline(symbol, df_m15_start, df_m15_end, 900)
                    self.logger.info("spotAPI.get_kline(symbol, df_m15_start, df_m15_end, 900)-2: %s,%s" %(symbol,rest))
            except Exception as e:
                self.logger.error(traceback.format_exc())
                self.logger.error(e)
                sleep(2)
                spotAPI = spot.SpotAPI(apiKey, apiSecret, passphrase, True)
                rest = spotAPI.get_kline(symbol, df_m15_start, df_m15_end, 900)
                self.logger.info("spotAPI.get_kline(symbol, df_m15_start, df_m15_end, 900)-2: %s,%s" %(symbol,rest))

            df_m15_2 = pd.read_json(json.dumps(rest), orient='records')
            df_m15_2.columns = ['datetime','open','high','low','close','vol']
            df_m15_2['symbol'] = symbol
            df_m15_2['datetime'] = df_m15_2.datetime.str.replace('T',' ').str.replace('.000Z','') 
            df_m15_2.index = df_m15_2.datetime
            df_m15_2 = df_m15_2[self.OKEX_MBAR_HEADER]

            df_m15 = pd.concat([df_m15_1, df_m15_2], axis=0)
            
            df_mn = self.convMxtoMn(df_m15,window_period)
            df_mn15 = self.convMxtoMn(df_m15,window_period_15min)

            try :
                #每次最多取200条，取1分钟数据
                spotAPI = spot.SpotAPI(apiKey, apiSecret, passphrase, True)
                rest = spotAPI.get_kline(symbol, '', '', 60)

                if (not rest) :
                    self.logger.info("spotAPI.get_kline(symbol, '', '', 60)-1: %s,%s" %(symbol,rest))
                    sleep(2)
                    spotAPI = spot.SpotAPI(apiKey, apiSecret, passphrase, True)
                    rest = spotAPI.get_kline(symbol, '', '', 60)
                    self.logger.info("spotAPI.get_kline(symbol, '', '', 60)-2: %s,%s" %(symbol,rest))
            except Exception as e:
                self.logger.error(traceback.format_exc())
                self.logger.error(e)
                sleep(2)
                spotAPI = spot.SpotAPI(apiKey, apiSecret, passphrase, True)
                rest = spotAPI.get_kline(symbol, '', '', 60)
                self.logger.info("spotAPI.get_kline(symbol, '', '', 60)-2: %s,%s" %(symbol,rest))

            df_m1 = pd.read_json(json.dumps(rest), orient='records')
            df_m1.columns = ['datetime','open','high','low','close','vol']
            df_m1['symbol'] = symbol
            df_m1['datetime'] = df_m1.datetime.str.replace('T',' ').str.replace('.000Z','') 
            df_m1.index = df_m1.datetime
            df_m1 = df_m1[self.OKEX_MBAR_HEADER]
            
            #分钟数据最新一条为不完整数据,实时数据重复接收倒数第二条数据，所以从第二条取
            df_m1 = df_m1[df_m1.index<self._trade[symbol]['datetime']]

            #基础模型数据-合成45分钟数据
            if len(df_m1[df_m1.index >= str(df_mn.ix[-1].datetime)]) == period_number:
                self._trade_m1_tmp[symbol] = pd.DataFrame()
                self._trade_mn[symbol] = df_mn
            else :
                self._trade_m1_tmp[symbol] = df_m1[df_m1.index >= str(df_mn.ix[-1].datetime)]
                self._trade_mn[symbol] = df_mn.ix[:-1]
            self.logger.debug("symbol,self._trade_mn[symbol],self._trade_m1_tmp[symbol]: %s,%s,%s" %(symbol, self._trade_mn[symbol], self._trade_m1_tmp[symbol]))

            #高频数据模型-合成15分钟数据
            if len(df_m1[df_m1.index >= str(df_mn15.ix[-1].datetime)]) == period_number_15min:
                self._trade_m1_tmp_m15[symbol] = pd.DataFrame()
                self._trade_m15[symbol] = df_mn15
            else :
                self._trade_m1_tmp_m15[symbol] = df_m1[df_m1.index >= str(df_mn15.ix[-1].datetime)]
                self._trade_m15[symbol] = df_mn15.ix[:-1]
            self.logger.debug("symbol,self._trade_m15[symbol],self._trade_m1_tmp_m15[symbol]: %s,%s,%s" %(symbol, self._trade_m15[symbol], self._trade_m1_tmp_m15[symbol]))

    #将1分钟数据转换成n分钟数据
    def convMxtoMn(self,df_m1,period) :
        df_m1.index = pd.to_datetime(df_m1.datetime)
        on = df_m1['open'].resample(period, label='left', closed = 'left').first()
        hn = df_m1[['high']].resample(period, label='left', closed = 'left').max()
        ln = df_m1[['low']].resample(period, label='left', closed = 'left').min()
        cn = df_m1[['close', 'symbol']].resample(period, label='left', closed = 'left').last()
        sn = df_m1[['vol']].resample(period, label='left', closed = 'left').sum()
        df_mn = pd.concat([on, hn, ln, cn, sn], axis=1)
        df_mn = df_mn.dropna()
        df_mn['datetime'] = df_mn.index
        df_mn = df_mn[self.MBAR_HEADER]
        return df_mn

def run():
    # Instantiating the WS will make it connect. Be sure to add your api_key/api_secret.
    ws = getOkexData(endPoint, symbol_list, apiKey, apiSecret, passphrase)

def setup_logger():
    # Prints logger info to terminal
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)  # Change this to DEBUG if you want a lot more info
    ch = logging.StreamHandler()
    fh = logging.FileHandler('./log/okex_trade_7_'+ datetime.datetime.today().strftime('%Y%m%d') +'.log')
    # create formatter
    formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
    formatter_fh = logging.Formatter("%(asctime)s : %(message)s")
    # add formatter to ch
    ch.setFormatter(formatter)
    fh.setFormatter(formatter_fh)
    logger.addHandler(ch)
    logger.addHandler(fh)
    return logger

#获取多品种交集矩阵
def get_mix_data(df_m15_dict,MBAR_HEADER_MA) :
    try:
        _df = pd.DataFrame()
        _df_mix = pd.DataFrame()
        for _symbol in code_list:
            if _symbol != quote_currency :
                if _symbol in df_m15_dict :
                    df_m15_dict[_symbol]['ma40'] = df_m15_dict[_symbol]['close'].rolling(40).mean().round(2)
                    _df = df_m15_dict[_symbol][-window_size-1:]
                else :
                    return False
                _df.index.names = ['timestamp']
                #获取多品种的时间索引交集
                if _df_mix.empty:
                    #创建cash除了datetime之外全部为0的df,接口要求
                    _df_mix = pd.DataFrame(np.zeros((len(_df.index),len(MBAR_HEADER_MA))), index=_df.index, columns=MBAR_HEADER_MA)
                    _df_mix.datetime = _df.datetime
                    _df_mix = pd.merge(_df_mix, _df, on='datetime', how='inner', suffixes=("","_"+_symbol))
                else :
                    _df_mix = pd.merge(_df_mix, _df, on='datetime', how='inner', suffixes=("","_"+_symbol))
    except Exception as e:
        self.logger.error(traceback.format_exc())
        self.logger.error(e)
    return _df_mix 

def model_output(df_mix):
    #各品种的多维度特征的最近的31个15分钟数据输入模型和上一次资金配置比例，输出资金配置比例
    #根据模型返回资金配比，调整持仓、调整开仓均价、取整+手续费+浮动盈亏调整输入模型资金配比
    global _log_df

    if _log_df.empty : 
        _pre_total = pd.DataFrame(init_total,columns=code_list) 
        _pre_volume = pd.DataFrame(init_volume, columns=code_list)
        _pre_open_avg = pd.DataFrame(init_open_avg, columns=code_list)
        _pre_close = pd.DataFrame(init_open_avg, columns=code_list) 
    else :
        if 'output_total' in _log_df :
            _pre_total = np.array([_log_df['output_total']])
        else :
            _pre_total = pd.DataFrame(init_total,columns=code_list) 

        if 'output_volume' in _log_df :
            _pre_volume = _log_df['output_volume']
        else :
            _pre_volume = pd.DataFrame(init_volume, columns=code_list)

        if 'now_open_avg' in _log_df :
            _pre_open_avg = _log_df['now_open_avg']
        else :
            _pre_open_avg = pd.DataFrame(init_open_avg, columns=code_list)

        if 'now_close' in _log_df :
            _pre_close = _log_df['now_close']
        else :
            _pre_close = pd.DataFrame(init_open_avg, columns=code_list) 

    _log_df = pd.DataFrame()

    #上一次资金配比总金额pre_total
    _log_df = pd.DataFrame(_pre_total,columns=code_list).T 
    _log_df.columns = ['pre_total']

    #获取特征属性的多品种的31条15分钟线数据矩阵，行转列取值为多维数组，多维数组降为一维数组
    state = df_mix.ix[1:,code_fields_list].T.values.flatten()
    pre_state = df_mix.ix[:len(df_mix)-2,code_fields_list].T.values.flatten()

    #将一维数组转化成指定的多维数组
    #field_size 代表的是特征的维数 3 [high,low,close]
    #code_size 表示的品种个数 3 ['XRP','ETH','LTC'] 
    #window_size 代表的是31个时间窗口
    #特征list,high最高价,low最低价,close收盘价
    state.shape = 1,field_size,code_size,window_size
    pre_state.shape = 1,field_size,code_size,window_size
    
    #获取当前15分钟的各品种数据
    _now_df = df_mix.ix[(len(df_mix)-1):(len(df_mix)-1)] 
    
    #当前时间
    _datetime = _now_df.datetime.iloc[0]

    #multiplicator 合约乘数, margin_ratio 保证金比率, open_fee_ratio 开仓手续费比率, 
    #open_fee_value 开仓手续费固定金额, close_fee_ratio 平仓手续费比率, close_fee_value 平仓手续费固定金额
    _dict = sDict[sDict.code_ap.isin(code_list)]
    _dict.index = _dict.code_ap
    _log_df = pd.merge(_log_df, _dict.iloc[:,1:], left_index=True, right_index=True, how='inner')
        
    #上一次持仓数量pre_volume
    _log_df['pre_volume']= _pre_volume.T 
    #上一次开仓均值 
    _log_df['pre_open_avg'] = _pre_open_avg.T
    #上一次close价格
    _log_df['pre_close'] = _pre_close.T
    #高频15分钟交易次数,默认为0
    _log_df['init_high_trade'] = 0 
    #当前收盘价now_close
    _now_close = _now_df.ix[:,code_close_list]
    _now_close.columns = code_list
    _log_df['now_close'] = _now_close.T
    _log_df.at[quote_currency,'now_close'] = 1

    #获取max close价格
    _max_df = df_mix.ix[1:].ix[:,code_close_list]
    _max_df.columns = code_list
    _max_close = _max_df.max()
    #max close
    _log_df['max_close'] = _max_close.T
    _log_df.at[quote_currency,'max_close'] = 1
    _log_df['max_close_ratio'] = _log_df['now_close'].div(_log_df['max_close'])-1  

    #当前持仓浮动价值=(收盘价-上一次开仓均价)*上一次持仓量*合约乘数 
    _log_df['now_total_fluctuation'] = _log_df.now_close.sub(_log_df.pre_open_avg).mul(_log_df.pre_volume).mul(_log_df.multiplicator)
    #当前持仓保证金=收盘价*上一次持仓数量*合约乘数*保证金比例 
    _log_df['now_total_hold'] = _log_df.now_close.mul(_log_df.pre_volume).mul(_log_df.multiplicator).mul(_log_df.margin_ratio)/100
    _log_df.at[quote_currency,'now_total_hold'] = _log_df.pre_total.ix[quote_currency] 
    #当前总持仓金额=现金+当前持仓价值(收盘价*上一次持仓量*合约乘数)
    _log_df['now_total'] = _log_df.now_close.mul(_log_df.pre_volume).mul(_log_df.multiplicator)
    #当前总价值现金=上一次总价值现金 
    _log_df.at[quote_currency,'now_total'] = _log_df.pre_total.ix[quote_currency] 

    #资金变化配置比例=当前总持仓金额/当前总持仓金额之和
    _log_df['now_ratio'] = _log_df.now_total.div(_log_df.now_total.sum())

    #######################################################################
    #输入持仓比例=上一次输出持仓比例 
    #_input_ratio = np.array([_log_df['pre_output_ratio'].T])
    #将各品种数据31个15分钟数据传入模型,获取当前时间的资金配置
    _output_ratio = brain.predict(state)
    _output_ratio_1 = [[0, 0, 0, 1, 0, 0]]
    _pre_ratio = brain.predict(pre_state)
    #######################################################################

    #模型输出上一个窗口资金配比pre_ratio
    _log_df['pre_ratio'] = pd.DataFrame(_pre_ratio,columns=code_list).T
    #模型输出资金配比output_ratio
    _log_df['base_ratio'] = pd.DataFrame(_output_ratio,columns=code_list).T

    #######################################################################
    #止损判断
    #1.出场条件,上一重仓币种和当前重仓币种任何一个比31窗口close最高价跌幅小于-4%,则所有换成现金
    #2.入场条件,调仓比率绝对值大于100%，且上一重仓币种和当前重仓币种任何一个比31窗口close最高价跌幅大于-4%
    #获得持仓量最大的币种dataframe中最大值的索引，可能有多个,randomly choose 1 index
    #max_now_ratio_symbol = np.random.choice(_log_df['pre_ratio'][_log_df['pre_ratio'] == _log_df['pre_ratio'].max()].index)
    #max_output_ratio_symbol = np.random.choice(_log_df['base_ratio'][_log_df['base_ratio'] == _log_df['base_ratio'].max()].index)
    #'close_'+max_now_ratio_symbol
    #'close_'+max_output_ratio_symbol
    #state['close_'+max_now_ratio_symbol].max()
    #_log_df['now_close'] 
    #state['close_'+max_output_ratio_symbol].max()
    #_log_df['now_close'][max_now_ratio_symbol]
    #_log_df['now_close'][max_output_ratio_symbol]
    #出场条件
    '''
    if ((_log_df['now_close'].div(_log_df['max_close'])-1)[np.random.choice(_log_df['pre_ratio'][_log_df['pre_ratio'] == _log_df['pre_ratio'].max()].index)] < -0.04) or ((_log_df['now_close'].div(_log_df['max_close'])-1)[np.random.choice(_log_df['base_ratio'][_log_df['base_ratio'] == _log_df['base_ratio'].max()].index)] < -0.04):
        _tmp_ratio = pd.DataFrame(np.zeros((1,len(code_list))),columns=code_list)
        _tmp_ratio[quote_currency] = 1.0
        _log_df['output_ratio'] = _tmp_ratio.T
    else :
        if (_log_df['base_ratio'][quote_currency] > 0.9) and (_log_df['base_ratio'].sub(_log_df['pre_ratio']).abs().sum() < 1) :
            _tmp_ratio = pd.DataFrame(np.zeros((1,len(code_list))),columns=code_list)
            _tmp_ratio[quote_currency] = 1.0
            _log_df['output_ratio'] = _tmp_ratio.T
        else :
            _log_df['output_ratio'] = pd.DataFrame(_output_ratio,columns=code_list).T
    '''
    #持现金
    '''
    if (_log_df['now_ratio'][quote_currency] > 0.9) :
        if ((_log_df['now_close'].div(_log_df['max_close'])-1)['ETH-USDT'] < -0.04) or ((_log_df['now_close'].div(_log_df['max_close'])-1)[np.random.choice(_log_df['base_ratio'][_log_df['base_ratio'] == _log_df['base_ratio'].max()].index)] < -0.04) or (_log_df['base_ratio'].sub(_log_df['pre_ratio']).abs().sum() < 1) :
            _tmp_ratio = pd.DataFrame(np.zeros((1,len(code_list))),columns=code_list)
            _tmp_ratio[quote_currency] = 1.0
            _log_df['output_ratio'] = _tmp_ratio.T
        else :
            _log_df['output_ratio'] = pd.DataFrame(_output_ratio,columns=code_list).T
    #持币
    else :
        if ((_log_df['now_close'].div(_log_df['max_close'])-1)[np.random.choice(_log_df['pre_ratio'][_log_df['pre_ratio'] == _log_df['pre_ratio'].max()].index)] < -0.04) or ((_log_df['now_close'].div(_log_df['max_close'])-1)[np.random.choice(_log_df['base_ratio'][_log_df['base_ratio'] == _log_df['base_ratio'].max()].index)] < -0.04):
            _tmp_ratio = pd.DataFrame(np.zeros((1,len(code_list))),columns=code_list)
            _tmp_ratio[quote_currency] = 1.0
            _log_df['output_ratio'] = _tmp_ratio.T
        else :
            _log_df['output_ratio'] = pd.DataFrame(_output_ratio,columns=code_list).T
    '''
    _log_df['output_ratio'] = pd.DataFrame(_output_ratio_1,columns=code_list).T

    logger.info('_log_df[pre_ratio],_log_df[base_ratio],_log_df[now_ratio],_log_df[output_ratio],_log_df[now_close],_log_df[max_close],(_log_df[now_close].div(_log_df[max_close])-1)--%s,%s,%s,%s,%s,%s,%s' %(_log_df['pre_ratio'],_log_df['base_ratio'],_log_df['now_ratio'],_log_df['output_ratio'],_log_df['now_close'],_log_df['max_close'],(_log_df['now_close'].div(_log_df['max_close'])-1)))

    #######################################################################

    #模型输出配比金额now_cash = 模型输出资金配比*当前总金额(现金+持仓)之和
    _log_df['output_cash'] = _log_df.output_ratio.mul(_log_df.now_total.sum())

    #当前1手保证金=当前收盘价*合约乘数*保证金比例
    _log_df['now_margin'] = _log_df.now_close.mul(_log_df.multiplicator).mul(_log_df.margin_ratio)/100
    #当前1手开仓手续费=当前收盘价*合约乘数*开仓手续费比例+1手开仓手续费现金
    _log_df['now_open_fee'] = _log_df.now_close.mul(_log_df.multiplicator).mul(_log_df.open_fee_ratio).add(_log_df.open_fee_value)
    #当前1手平仓手续费=当前收盘价*合约乘数*平仓手续费比例+1手平仓手续费现金
    _log_df['now_close_fee'] = _log_df.now_close.mul(_log_df.multiplicator).mul(_log_df.close_fee_ratio).add(_log_df.close_fee_value)
    #当前1手开仓成本=1手保证金+1手开仓手续费 
    #1手开仓成本 open_cost = 当前收盘价*合约乘数*保证金比率/100+当前收盘价*合约乘数*开仓手续费比率+开仓手续费固定费用
    _log_df['now_open_cost'] = _log_df.now_margin.add(_log_df.now_open_fee)
    #当前1手平仓收益=当前收盘价*合约乘数-1手平仓手续费
    #当前1手平仓收益close_cost = 当前收盘价*合约乘数-(当前收盘价*合约乘数*平仓手续费比率+平仓手续费固定费用)
    _log_df['now_close_cost'] = _log_df.now_close.mul(_log_df.multiplicator).sub(_log_df.now_close_fee) 
    #当前1手平仓浮动盈亏=(收盘价-开盘均价)*合约乘数-手续费
    _log_df['now_close_fluctuation'] = _log_df.now_close.sub(_log_df.pre_open_avg).mul(_log_df.multiplicator).sub(_log_df.now_close_fee) 

    #实时追单标记,默认为0
    _log_df['position_realtime_order'] = 0 

    #模型输出配比后资金变化量=模型输出配比金额-(动态保证金-当前收盘价的持仓成本:上一次持仓量*当前1手保证金)
    #_log_df['output_change'] = _log_df.output_cash.sub(_log_df.pre_volume.mul(_log_df.now_margin))
    #模型输出配比后资金变化量=模型输出配比金额-(收盘价*上一次持仓量*合约乘数*保证金比例
    _log_df['output_change'] = _log_df.output_cash.sub(_log_df.now_total)
    _log_df['output_change_ratio'] = _log_df.output_change.div(_log_df.output_change[_log_df.output_change>0].sum())

    #模型输出配比持仓变化量(买入和卖出的数量)=
    #资金变化量为正:资金变化金额/当前1手开仓(保证金+手续费)成本,
    #资金变化量为负:资金变化金额/当前1手保证金成本
    #持仓变化量=当前资金配比金额/当前1手保证金成本-上一次持仓量 ,当前持仓配比金额=上一次持仓量*当前1手保证金成本+持仓变化金额
    #持仓变化量=(上一次持仓量*当前1手保证金成本+持仓变化金额)/当前1手保证金成本-上一次持仓量=上一次持仓变化量-持仓变化金额/当前1手保证金成本-上一次持仓变化量=持仓变化金额/当前1手保证金成本
    #_log_df['output_change_volume'] = _log_df.output_change[_log_df.output_change>0].floordiv(_log_df.now_open_cost).fillna(0).add(_log_df.output_change[_log_df.output_change<0].floordiv(_log_df.now_margin).fillna(0)) 
    #货币购买是从基础币种收取手续费，例如千分之二手续费购买基础币2个，实际买到1.998个
    _log_df['output_change_volume'] = _log_df.output_change[_log_df.output_change>=0].div(_log_df.now_open_cost).fillna(0).add(_log_df.output_change[_log_df.output_change<0].div(_log_df.now_close_cost).fillna(0)) 
    _log_df.at[quote_currency,'output_change_volume'] = 0
    #根据各币种保留小数位舍去取整
    _log_df['floor_change_volume'] = 0.0 
    for i in list(range(len(_log_df['output_change_volume']))) : 
        _symbol = _log_df['output_change_volume'].index[i]
        if _symbol not in symbol_list : continue 
        #不等于报价货币的交易币种,或者symbol为''或者symbol需要挂单币种
        if (_symbol != quote_currency) and (_symbol in symbol_list) :
            #理论调仓量按照系统要求保留位数舍去取整(正数舍去,负数的绝对值为进1取整)
            _volume = math.floor(_log_df['output_change_volume'][i]*(10**init_precision[_symbol]['vol'])+0.1)/(10**init_precision[_symbol]['vol'])
            #判断volume是否大于最小值
            if abs(_volume) < float(init_precision[_symbol]['min_vol']) :
                _volume = 0
            _log_df.at[_symbol, 'floor_change_volume'] = _volume

    #实时-目标调仓价格
    _log_df['realtime_now_close'] = copy.deepcopy(_log_df.now_close) 
    #实时-目标调仓金额
    _log_df['realtime_output_change'] = copy.deepcopy(_log_df.output_change) 
    #实时-更新已成交量
    _log_df['realtime_change_volume'] = 0.0 
    #实时-更新未成交量
    _log_df['realtime_nofilled_volume'] = copy.deepcopy(_log_df.floor_change_volume) 
    #实时-更新下单未成交量
    _log_df['realtime_open_nofilled_volume'] = 0.0 
    #实时-更新未下单量
    _log_df['realtime_noopen_volume'] = copy.deepcopy(_log_df.floor_change_volume) 
    #实时-总close滑点成本
    _log_df['realtime_total_cost'] = 0.0
    #实时-已成交close滑点成本
    _log_df['realtime_filled_cost'] = 0.0
    #实时-未成交close滑点成本
    _log_df['realtime_nofilled_cost'] = 0.0

    #实时更新没有成交的top挂单价格
    _log_df['realtime_nofilled_top_price'] = 0.0

    #实时成交比率
    _log_df['realtime_filled_ratio'] = 0.0
    #实时成交速率
    _log_df['realtime_filled_rate'] = 0.0
    #临时-实时下单未成交量
    _log_df['tmp_realtime_open_nofilled_volume'] = 0.0
    #临时-实时已成交量
    _log_df['tmp_realtime_change_volume'] = 0.0
    #临时-实时close滑点成本
    _log_df['tmp_realtime_filled_cost'] = 0.0

def total_output(position_dict, order_dict): 
    global _log_df

    #实际--模型输出配比持仓变化量
    #_log_df['position_change_volume'] = copy.deepcopy(_log_df.output_change_volume)
    _log_df['position_change_volume'] = 0.0 
    #实际--模型输出配比后资金变化量
    #_log_df['position_output_change'] = copy.deepcopy(_log_df.output_change) 
    _log_df['position_output_change'] = 0.0 

    _log_df['tmp_position_change_volume'] = 0.0 
    _log_df['tmp_position_output_change'] = 0.0 

    #{'table': 'spot/order', 'data': [{'client_oid': '', 'filled_notional': '524.5295426', 'filled_size': '0.1003385', 'instrument_id': 'BTC-USDT', 'last_fill_px': '5227.6', 'last_fill_qty': '0.0013758', 'last_fill_time': '2019-04-18T12:45:10.816Z','margin_trading': '1', 'notional': '', 'order_id': '2677506504460288', 'order_type': '0', 'price': '5227.6', 'side': 'buy', 'size': '0.17647342', 'status': 'part_filled', 'timestamp': '2019-04-18T12:45:07.000Z', 'type': 'limit'}]}
    #{'table': 'spot/order', 'data': [{'client_oid': '', 'filled_notional': '922.532450392','filled_size': '0.17647342', 'instrument_id': 'BTC-USDT', 'last_fill_px': '5227.6', 'last_fill_qty': '0.07613492', 'last_fill_time': '2019-04-18T12:46:01.652Z','margin_trading': '1', 'notional': '', 'order_id': '2677506504460288', 'order_type': '0', 'price': '5227.6', 'side': 'buy', 'size': '0.17647342', 'status': 'filled', 'timestamp': '2019-04-18T12:45:07.000Z', 'type': 'limit'}]}
    #参数名	类型	描述
    #order_id	long	订单ID
    #client_oid	String	由用户设置的订单ID
    #price	String	价格
    #size	String	交易货币数量
    #notional	String	买入金额，市价买入时返回
    #instrument_id	String	币对名称
    #side	String	buy or sell
    #type	String	limit,market(默认是limit)
    #timestamp	String	订单创建时间
    #filled_size	String	已成交数量
    #filled_notional	String	已成交金额
    #status	String	订单状态( open:未成交 part_filled:部分成交 filled:已成交 cancelled:已撤销 failure:订单失败 )
    #margin_trading	String	1 币币交易订单. 2 杠杆交易订单
    #order_type	String	0：普通委托 1：只做Maker（Post only） 2：全部成交或立即取消（FOK） 3：立即成交并取消剩余（IOC）
    #last_fill_px	String	最新成交价格 （如果没有，推0）
    #last_fill_qty	String	最新成交数量（如果没有，推0）
    #last_fill_time	String	最新成交时间（如果没有，推1970-01-01T00:00:00.000Z）

    for (symbol,order_values) in order_dict.items() :
        if symbol not in symbol_list : continue 
        _log_df.at[symbol,'position_change_volume'] = 0.0
        _log_df.at[symbol,'position_output_change'] = 0.0
        for (order_id,order_value) in order_values.items() :
            _log_df.at[symbol,'tmp_position_change_volume'] = 0.0
            _log_df.at[symbol,'tmp_position_output_change'] = 0.0
            for (order_type,order_info) in order_value.items() :
                #filled in filled和part_filled
                #按照成交顺序订阅更新单一订单的已成交数量和已成交金额，filled_size已成交数量,filled_notional已成交金额
                if order_type == 'filled':
                    if ('side' in order_info) and (order_info['side'] == 'sell') :
                        _log_df.at[symbol, 'tmp_position_change_volume'] = -float(order_info['filled_size'])
                        _log_df.at[symbol, 'tmp_position_output_change'] = -float(order_info['filled_notional'])
                    elif ('side' in order_info) and (order_info['side'] == 'buy') : 
                        _log_df.at[symbol, 'tmp_position_change_volume'] = float(order_info['filled_size'])
                        _log_df.at[symbol, 'tmp_position_output_change'] = float(order_info['filled_notional'])
                    else :
                        logger.info('filled-amount not sell-limit and not buy-limit')
                elif (order_type != 'filled') and ('part_filled' in order_type) : 
                    if ('side' in order_info) and (order_info['side'] == 'sell') :
                        _log_df.at[symbol, 'tmp_position_change_volume'] = -float(order_info['filled_size'])
                        _log_df.at[symbol, 'tmp_position_output_change'] = -float(order_info['filled_notional'])
                    elif ('side' in order_info) and (order_info['side'] == 'buy') : 
                        _log_df.at[symbol, 'tmp_position_change_volume'] = float(order_info['filled_size'])
                        _log_df.at[symbol, 'tmp_position_output_change'] = float(order_info['filled_notional'])
                    else :
                        logger.info('part_filled-amount not sell-limit and not buy-limit')
            #同一币对多个订单的已成交数量和已成交金额加和
            _log_df.at[symbol, 'position_change_volume'] += _log_df.at[symbol, 'tmp_position_change_volume']
            _log_df.at[symbol, 'position_output_change'] += _log_df.at[symbol, 'tmp_position_output_change'] 

    _log_df.at[quote_currency,'position_output_change'] = -_log_df.position_output_change[1:].sum() 

    #取整--实际持仓理论资金变化量
    _log_df['floor_output_change'] = _log_df.position_change_volume.mul(_log_df.now_close)

    #实际--买入价格滑点浮盈,资金变化量理论与实际差值
    _log_df['position_change_fluctuation'] = _log_df.floor_output_change.sub(_log_df.position_output_change)
    _log_df.at[quote_currency,'position_change_fluctuation'] = _log_df.position_change_fluctuation[1:].sum() 

    #模型输出配比总持仓量=上一次总持仓量+持仓变化量
    _log_df['output_volume'] = _log_df.pre_volume.add(_log_df.position_change_volume) 
    #现金总量=上一次现金总量+实际模型输出配比持仓变化量+实际模型输出配比后现金变化量
    _log_df.at[quote_currency,'output_volume'] = _log_df.pre_volume.ix[quote_currency]+_log_df.position_change_volume.ix[quote_currency]+_log_df.position_output_change.ix[quote_currency]

    #实际--模型输出配比总持仓量
    _log_df['position_output_volume'] = copy.deepcopy(_log_df.output_volume) 
    for base_currency in base_list :
        if base_currency in position_dict :
            _log_df.at[base_currency+"-"+quote_currency, 'position_output_volume'] = position_dict[base_currency]
    if quote_currency in position_dict :
        _log_df.at[quote_currency,'position_output_volume'] = position_dict[quote_currency]

    #实际--查询验证各币种持仓量
    _log_df['query_output_volume'] = 0.0 
    spotAPI = spot.SpotAPI(apiKey, apiSecret, passphrase, True)
    balance_result = spotAPI.get_account_info()

    #参数名	类型	描述
    #currency	String	币种
    #balance	String	余额
    #hold	String	冻结(不可用)
    #available	String	可用于交易的数量
    #id	        String	账户ID
    #币币账户信息接口返回frozen ,hold和holds参数值相同，以hold为准
    #[{"frozen": "0", "hold": "0", "id": "9196334", "currency": "USDT", "balance": "200", "available": "200", "holds": "0"}]

    try :
        if balance_result :
            logger.info('获取当前账户资产成功!')
            for val in balance_result :
                if val['currency'] == quote_currency :
                    logger.info('币种%s,资产%s' %(val['currency'],float(val['balance'])))
                    _log_df.at[quote_currency, 'query_output_volume'] = float(val['balance']) 
                elif val['currency']+"-"+quote_currency in code_list :
                    logger.info('币种%s,资产%s' %(val['currency'],float(val['balance'])))
                    _log_df.at[val['currency']+"-"+quote_currency, 'query_output_volume'] = float(val['balance']) 
        else :
            logger.info('获取当前账户资产失败 %s' % (balance_result))

        #当前资金变化持仓手续费=增仓品种(持仓变化量*开仓手续费)+减仓品种(持仓变化量*平仓手续费)
        _log_df['output_change_fee'] = _log_df.position_change_volume[_log_df.position_change_volume>0].mul(_log_df.now_open_fee).fillna(0).add(_log_df.position_change_volume[_log_df.position_change_volume<0].mul(_log_df.now_close_fee).abs().fillna(0))

        #模型输出配比总价值=模型输出配比持仓量*当前1手保证金
        _log_df['output_total'] = _log_df.output_volume.mul(_log_df.now_margin)
        #现金价值=当前总价值之和-模型输出配比总价值非cash之和-模型输出持仓变化手续费
        #_log_df.at[quote_currency,'output_total'] = _log_df.now_total.sum()-_log_df.output_total[1:].sum()-_log_df.output_change_fee[1:].sum()
        _log_df.at[quote_currency,'output_total'] = _log_df.now_total.ix[quote_currency]+_log_df.position_output_change.ix[quote_currency]

        #实际--模型输出配比总价值
        _log_df['position_output_total'] = _log_df.now_total.add(_log_df.position_output_change) 

        #当前开仓均价=增仓品种(当前增仓变化量*收盘价+上一次持仓量*开仓均价-当前持仓变化量*1手开仓手续费)/(上一次持仓量+当前持仓变化量),
        #减仓品种(上一次开仓均价)
        _log_df['now_open_avg'] = 0.0
        _log_df['now_open_avg'] = copy.deepcopy(_log_df.now_close) 

        #资金变化的取整资金配置比例
        _log_df['now_last_ratio'] = _log_df.output_total.div(_log_df.output_total.sum())

        init_dict = hold_data_load()
        if init_dict and ('init_high_trade' in init_dict) :
            _log_df['init_high_trade'] = pd.DataFrame([init_dict['init_high_trade']], columns=code_list).T
        logger.info('total_output finish!')
    except Exception as e:
        self.logger.error(traceback.format_exc())
        self.logger.error(e)

#保存初始化文件
def hold_data_open(logDict):
    #持久化文件
    hlod_name = './config/hold_data_okex'
    fbl = open(hlod_name, 'wb')
    saveObj = logDict
    pickle.dump(saveObj, fbl)
    fbl.close()

#加载初始化文件
def hold_data_load():
    #持久化文件
    hlod_name = './config/hold_data_okex'
    if os.path.exists(hlod_name):
        fbl = open(hlod_name, 'rb')
        loadObj = pickle.load(fbl)
        return loadObj
    else :
        return False

#初始化获取总金额、币种持仓量
def init_total_volume_avg():
    balance_dict = {}

    load_dict = hold_data_load()
    if load_dict :
        logger.info('获取初始化文件成功! %s' % (load_dict))
        init_total[0] = load_dict['init_total']
    else :
        logger.info('获取初始化文件失败!')
    
    spotAPI = spot.SpotAPI(apiKey, apiSecret, passphrase, True)
    balance_result = spotAPI.get_account_info()

    #参数名	类型	描述
    #currency	String	币种
    #balance	String	余额
    #hold	String	冻结(不可用)
    #available	String	可用于交易的数量
    #id	        String	账户ID
    #币币账户信息接口返回frozen ,hold和holds参数值相同，以hold为准
    #[{"frozen": "0", "hold": "0", "id": "9196334", "currency": "USDT", "balance": "200", "available": "200", "holds": "0"}]

    if balance_result :
        logger.info('获取当前账户资产成功!')
        for val in balance_result :
            if val['currency'] == quote_currency :
                balance_dict[quote_currency] = float(val['balance'])
                init_volume[0][code_list.index(quote_currency)] = float(val['balance'])
            elif val['currency']+"-"+quote_currency in code_list :
                balance_dict[val['currency']+"-"+quote_currency] = float(val['balance']) 
                init_volume[0][code_list.index(val['currency']+"-"+quote_currency)] = float(val['balance'])
            else :
                balance_dict[val['currency']+"-"+quote_currency] = float(val['balance']) 
    else :
        logger.info('获取当前账户资产失败 %s' % (balance_result))

def get_precision():
    spotAPI = spot.SpotAPI(apiKey, apiSecret, passphrase, True)
    _get_symbols = spotAPI.get_coin_info()
    for val in _get_symbols:
        if val['instrument_id'] in symbol_list :
            init_precision[val['instrument_id']] = {'price':len(str(val['tick_size']))-2,'vol':len(str(val['size_increment']))-2,'min_vol':val['min_size']}

#解压缩处理
def inflate(data):
    decompress = zlib.decompressobj(
            -zlib.MAX_WBITS  # see above
    )
    inflated = decompress.decompress(data)
    inflated += decompress.flush()
    return inflated

#获取服务器时间
def get_server_time():
    url = c.API_URL + c.SERVER_TIMESTAMP_URL
    response = requests.get(url)
    if response.status_code == 200:
        return response.json()['iso']
    else:
        return datetime.datetime.utcnow().isoformat() 

#服务器时间转换成时间戳
def server_timestamp():
    try :
        server_time = get_server_time()
        parsed_t = dp.parse(server_time)
        timestamp = parsed_t.timestamp()
        return timestamp
    except Exception as re:
        print('检测出异常{}'.format(re))
        return time.time() 

if __name__ == "__main__":
    #设置dataframe显示宽度
    pd.set_option('display.width', 1000)  # 设置字符显示宽度
    pd.set_option('display.max_colwidth',1000)
    pd.set_option('display.max_rows',500) # 设置显示最大行
    pd.set_option('display.max_columns',500)

    logger = setup_logger()

    #endPoint = TRADE_URL 
    #apiKey = ACCESS_KEY 
    #apiSecret = SECRET_KEY 
    endPoint = c.ENDPOINT 
    apiKey = c.API_KEY 
    apiSecret = c.API_SECRET 
    passphrase = c.PASSPHRASE 

    #--init_model-------------------------------------------------------------------
    #交易货币list,eth以太币,eos柚子币,bch比特现金,trx波场币,xrp瑞波币,ltc莱特币,btc比特币
    #base_list = ['ETH','EOS','BCH','TRX','XRP','LTC','BTC']
    base_list = c.BASE_LIST 
    #计价货币,usdt美元代币
    quote_currency = c.QUOTE_CURRENCY 
    #计价货币持仓比例O
    quote_currency_ratio = c.QUOTE_CURRENCY_RATIO 
    #点卡货币代码
    #point_currency = 'OKDK'
    #交易品种list,交易品种=交易货币+计价货币 
    symbol_list = []
    for bc in base_list :
        symbol_list.append(bc+"-"+quote_currency) 
    #品种list,第一位默认计价货币
    #code_list = ['USDT','ETH-USDT','EOS-USDT','BCH-USDT','LTC-USDT','BTC-USDT']
    code_list = [quote_currency] + symbol_list
    #计价货币和交易品种的基础信息
    #symbols_confile = './config/okex_config.csv'
    symbols_confile = c.OK_SYMBOLS_CONFILE 
    #获取计价货币和交易品种的配置信息
    sDict = pd.read_csv(symbols_confile)

    #基础交易模型
    #模型配置
    cfg_path = c.OK_CFG_PATH 
    #cfg_path = './config/net_config.json.17700'
    #模型路径
    model = c.OK_MODEL 
    #model = './model/model.ckpt-17700'
    #初始化模型
    brain = agent(cfg_path,model)

    #高频交易模型
    #判断条件15分钟btc交易量大于1600,触发11个bar的15分钟
    #模型配置
    cfg_path_15min = c.OK_CFG_PATH_15MIN 
    model_15min = c.OK_MODEL_15MIN
    if cfg_path_15min and model_15min : 
        brain_15min = agent(cfg_path_15min,model_15min)

    #field_size 代表的是特征的维数 3 [high,low,close]
    #code_size 表示的品种个数 3 ['XRP','ETH','LTC'] 
    #window_size 代表的是时间窗的长度31个15分钟多品种交集时间数据
    #特征list,high最高价,low最低价,close收盘价
    field_list = c.FIELD_LIST 
    field_size = len(field_list) 
    code_size = len(code_list)-1 
    window_size = c.WINDOW_SIZE 

    #基础交易模型-单时间窗口时间长度 resample时间配置 周期时间+周期单位，例如：45分钟 '45min'
    period_number = c.PERIOD_NUMBER 
    period_unit = c.PERIOD_UNIT 
    window_period = str(period_number)+period_unit

    #高频交易模型-15分钟窗口数据
    period_number_15min = c.PERIOD_NUMBER_15MIN 
    period_unit_15min = c.PERIOD_UNIT_15MIN 
    window_period_15min = str(period_number_15min)+period_unit_15min

    #根据传递特征字段list，获取对应多品种的特征字段名称
    #根据close字段，获取对应多品种的特征字段名称
    code_fields_list = []
    code_close_list = []
    for _field in field_list :
        for _symbol in code_list:
            if _symbol != quote_currency :
                code_fields_list.append(_field + "_" + _symbol)
                if _field == 'close' :
                    code_close_list.append('close_' + _symbol)
            else :
                if _field == 'close' :
                    code_close_list.append('close')
    
    _log_df = pd.DataFrame()

    #初始资金金额,持仓量,购买均价
    init_total = np.zeros((1,len(code_list)))
    init_volume = np.zeros((1,len(code_list))) 
    init_open_avg = np.zeros((1,len(code_list))) 
    init_open_avg[0][0] = 1

    #根据历史成交订单,初始现金金额,持仓量,购买均价
    init_total_volume_avg()
    logger.info('$$$position$$$,%s,%s,%s' % (init_total,init_volume,init_open_avg))
    init_dict = {}

    #判断存在上一次total数据:当前交易币种持仓-(除交易币种外的上一次各币种持仓折算交易币种额度的加和 + 交易币种持仓量) * 交易币种预留比例
    if sum(init_total[0][1:len(code_list)]) > 0 :
        init_total[0][0] = init_volume[0][0]-(sum(init_total[0][1:len(code_list)])+init_volume[0][0])*quote_currency_ratio
        logger.info('$$$position-auto$$$,%s,%s,%s' % (init_total,init_volume,init_open_avg))
    else :
        init_total[0][0] = init_volume[0][0]-10
        logger.info('$$$position-auto-no-total$$$,%s,%s,%s' % (init_total,init_volume,init_open_avg))

    #指定初始金额
    #init_total = np.array([[-1.0,0,0,0,0,0,0,0]])
    #logger.info('$$$position-hand$$$,%s,%s,%s' % (init_total,init_volume,init_open_avg))
    
    #初始化各品种价格和量精度
    init_precision = {}
    get_precision()
    logger.info('init_precision:%s' % (init_precision))

    run()
